You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MAPIMessage.java 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hsmf;
  16. import java.io.File;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.UnsupportedEncodingException;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Calendar;
  23. import java.util.List;
  24. import java.util.regex.Matcher;
  25. import java.util.regex.Pattern;
  26. import org.apache.logging.log4j.LogManager;
  27. import org.apache.logging.log4j.Logger;
  28. import org.apache.poi.POIReadOnlyDocument;
  29. import org.apache.poi.hmef.attribute.MAPIRtfAttribute;
  30. import org.apache.poi.hsmf.datatypes.AttachmentChunks;
  31. import org.apache.poi.hsmf.datatypes.AttachmentChunks.AttachmentChunksSorter;
  32. import org.apache.poi.hsmf.datatypes.ByteChunk;
  33. import org.apache.poi.hsmf.datatypes.Chunk;
  34. import org.apache.poi.hsmf.datatypes.ChunkGroup;
  35. import org.apache.poi.hsmf.datatypes.Chunks;
  36. import org.apache.poi.hsmf.datatypes.MAPIProperty;
  37. import org.apache.poi.hsmf.datatypes.NameIdChunks;
  38. import org.apache.poi.hsmf.datatypes.PropertyValue;
  39. import org.apache.poi.hsmf.datatypes.PropertyValue.LongPropertyValue;
  40. import org.apache.poi.hsmf.datatypes.PropertyValue.TimePropertyValue;
  41. import org.apache.poi.hsmf.datatypes.RecipientChunks;
  42. import org.apache.poi.hsmf.datatypes.RecipientChunks.RecipientChunksSorter;
  43. import org.apache.poi.hsmf.datatypes.StringChunk;
  44. import org.apache.poi.hsmf.datatypes.Types;
  45. import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
  46. import org.apache.poi.hsmf.parsers.POIFSChunkParser;
  47. import org.apache.poi.poifs.filesystem.DirectoryNode;
  48. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  49. import org.apache.poi.util.CodePageUtil;
  50. import org.apache.poi.util.LocaleUtil;
  51. import static org.apache.logging.log4j.util.Unbox.box;
  52. /**
  53. * Reads an Outlook MSG File in and provides hooks into its data structure.
  54. *
  55. * If you want to develop with HSMF, you might find it worth getting
  56. * some of the Microsoft public documentation, such as:
  57. *
  58. * [MS-OXCMSG]: Message and Attachment Object Protocol Specification
  59. */
  60. public class MAPIMessage extends POIReadOnlyDocument {
  61. /**
  62. * A MAPI file can be an email (NOTE) or a number of other types
  63. */
  64. public enum MESSAGE_CLASS {
  65. APPOINTMENT,
  66. CONTACT,
  67. NOTE,
  68. POST,
  69. STICKY_NOTE,
  70. TASK,
  71. UNKNOWN,
  72. UNSPECIFIED
  73. }
  74. /** For logging problems we spot with the file */
  75. private static final Logger LOG = LogManager.getLogger(MAPIMessage.class);
  76. private Chunks mainChunks;
  77. private NameIdChunks nameIdChunks;
  78. private RecipientChunks[] recipientChunks;
  79. private AttachmentChunks[] attachmentChunks;
  80. private boolean returnNullOnMissingChunk;
  81. /**
  82. * Constructor for creating new files.
  83. */
  84. public MAPIMessage() {
  85. // TODO - make writing possible
  86. super(new POIFSFileSystem());
  87. }
  88. /**
  89. * Constructor for reading MSG Files from the file system.
  90. *
  91. * @param filename Name of the file to read
  92. * @throws IOException on errors reading, or invalid data
  93. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  94. * input format
  95. */
  96. public MAPIMessage(String filename) throws IOException {
  97. this(new File(filename));
  98. }
  99. /**
  100. * Constructor for reading MSG Files from the file system.
  101. *
  102. * @param file The file to read from
  103. * @throws IOException on errors reading, or invalid data
  104. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  105. * input format
  106. */
  107. public MAPIMessage(File file) throws IOException {
  108. this(new POIFSFileSystem(file));
  109. }
  110. /**
  111. * Constructor for reading MSG Files from an input stream.
  112. *
  113. * <p>Note - this will buffer the whole message into memory
  114. * in order to process. For lower memory use, use {@link #MAPIMessage(File)}
  115. *
  116. * @param in The InputStream to buffer and then read from
  117. * @throws IOException on errors reading, or invalid data
  118. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  119. * input format
  120. */
  121. public MAPIMessage(InputStream in) throws IOException {
  122. this(new POIFSFileSystem(in));
  123. }
  124. /**
  125. * Constructor for reading MSG Files from a POIFS filesystem
  126. *
  127. * @param fs Open POIFS FileSystem containing the message
  128. * @throws IOException on errors reading, or invalid data
  129. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  130. * input format
  131. */
  132. public MAPIMessage(POIFSFileSystem fs) throws IOException {
  133. this(fs.getRoot());
  134. }
  135. /**
  136. * Constructor for reading MSG Files from a certain
  137. * point within a POIFS filesystem
  138. * @param poifsDir Directory containing the message
  139. * @throws IOException on errors reading, or invalid data
  140. * @throws RuntimeException a number of runtime exceptions can be thrown, especially if there are problems with the
  141. * input format
  142. */
  143. public MAPIMessage(DirectoryNode poifsDir) throws IOException {
  144. super(poifsDir);
  145. // Grab all the chunks
  146. ChunkGroup[] chunkGroups = POIFSChunkParser.parse(poifsDir);
  147. // Grab interesting bits
  148. ArrayList<AttachmentChunks> attachments = new ArrayList<>();
  149. ArrayList<RecipientChunks> recipients = new ArrayList<>();
  150. for(ChunkGroup group : chunkGroups) {
  151. // Should only ever be one of each of these
  152. if(group instanceof Chunks) {
  153. mainChunks = (Chunks)group;
  154. } else if(group instanceof NameIdChunks) {
  155. nameIdChunks = (NameIdChunks)group;
  156. } else if(group instanceof RecipientChunks) {
  157. recipients.add( (RecipientChunks)group );
  158. }
  159. // Can be multiple of these - add to list(s)
  160. if(group instanceof AttachmentChunks) {
  161. attachments.add( (AttachmentChunks)group );
  162. }
  163. }
  164. attachmentChunks = attachments.toArray(new AttachmentChunks[0]);
  165. recipientChunks = recipients.toArray(new RecipientChunks[0]);
  166. // Now sort these chunks lists so they're in ascending order,
  167. // rather than in random filesystem order
  168. Arrays.sort(attachmentChunks, new AttachmentChunksSorter());
  169. Arrays.sort(recipientChunks, new RecipientChunksSorter());
  170. }
  171. /**
  172. * Gets a string value based on the passed chunk.
  173. * @throws ChunkNotFoundException if the chunk isn't there
  174. */
  175. public String getStringFromChunk(StringChunk chunk) throws ChunkNotFoundException {
  176. if(chunk == null) {
  177. if(returnNullOnMissingChunk) {
  178. return null;
  179. } else {
  180. throw new ChunkNotFoundException();
  181. }
  182. }
  183. return chunk.getValue();
  184. }
  185. /**
  186. * Gets the plain text body of this Outlook Message
  187. * @return The string representation of the 'text' version of the body, if available.
  188. * @throws ChunkNotFoundException If the text-body chunk does not exist and
  189. * returnNullOnMissingChunk is set
  190. */
  191. public String getTextBody() throws ChunkNotFoundException {
  192. return getStringFromChunk(mainChunks.getTextBodyChunk());
  193. }
  194. /**
  195. * Gets the html body of this Outlook Message, if this email
  196. * contains a html version.
  197. * @return The string representation of the 'html' version of the body, if available.
  198. * @throws ChunkNotFoundException If the html-body chunk does not exist and
  199. * returnNullOnMissingChunk is set
  200. */
  201. public String getHtmlBody() throws ChunkNotFoundException {
  202. ByteChunk htmlBodyBinaryChunk = mainChunks.getHtmlBodyChunkBinary();
  203. if (htmlBodyBinaryChunk != null) {
  204. List<PropertyValue> cpid = mainChunks.getProperties().get(MAPIProperty.INTERNET_CPID);
  205. if (cpid != null && cpid.size() > 0) {
  206. int codepage = ((LongPropertyValue) cpid.get(0)).getValue();
  207. try {
  208. String encoding = CodePageUtil.codepageToEncoding(codepage, true);
  209. byte[] htmlBodyBinary = htmlBodyBinaryChunk.getValue();
  210. return new String(htmlBodyBinary, encoding);
  211. } catch (UnsupportedEncodingException e) {
  212. LOG.atWarn().log("HTML body binary: Invalid codepage ID {} set for the message via {}, ignoring", box(codepage), MAPIProperty.INTERNET_CPID);
  213. }
  214. }
  215. return htmlBodyBinaryChunk.getAs7bitString();
  216. }
  217. return getStringFromChunk(mainChunks.getHtmlBodyChunkString());
  218. }
  219. /**
  220. * Gets the RTF Rich Message body of this Outlook Message, if this email
  221. * contains a RTF (rich) version.
  222. * @return The string representation of the 'RTF' version of the body, if available.
  223. * @throws ChunkNotFoundException If the rtf-body chunk does not exist and
  224. * returnNullOnMissingChunk is set
  225. */
  226. public String getRtfBody() throws ChunkNotFoundException {
  227. ByteChunk chunk = mainChunks.getRtfBodyChunk();
  228. if(chunk == null) {
  229. if(returnNullOnMissingChunk) {
  230. return null;
  231. } else {
  232. throw new ChunkNotFoundException();
  233. }
  234. }
  235. try {
  236. MAPIRtfAttribute rtf = new MAPIRtfAttribute(
  237. MAPIProperty.RTF_COMPRESSED, Types.BINARY.getId(), chunk.getValue()
  238. );
  239. return rtf.getDataString();
  240. } catch(IOException e) {
  241. throw new RuntimeException("Shouldn't happen", e);
  242. }
  243. }
  244. /**
  245. * Gets the subject line of the Outlook Message
  246. * @throws ChunkNotFoundException If the subject-chunk does not exist and
  247. * returnNullOnMissingChunk is set
  248. */
  249. public String getSubject() throws ChunkNotFoundException {
  250. return getStringFromChunk(mainChunks.getSubjectChunk());
  251. }
  252. /**
  253. * Gets the display value of the "FROM" line of the outlook message
  254. * This is not the actual address that was sent from but the formatted display of the user name.
  255. * @throws ChunkNotFoundException If the from-chunk does not exist and
  256. * returnNullOnMissingChunk is set
  257. */
  258. public String getDisplayFrom() throws ChunkNotFoundException {
  259. return getStringFromChunk(mainChunks.getDisplayFromChunk());
  260. }
  261. /**
  262. * Gets the display value of the "TO" line of the outlook message.
  263. * If there are multiple recipients, they will be separated
  264. * by semicolons.
  265. * This is not the actual list of addresses/values that will be
  266. * sent to if you click Reply in the email - those are stored
  267. * in {@link RecipientChunks}.
  268. * @throws ChunkNotFoundException If the to-chunk does not exist and
  269. * returnNullOnMissingChunk is set
  270. */
  271. public String getDisplayTo() throws ChunkNotFoundException {
  272. return getStringFromChunk(mainChunks.getDisplayToChunk());
  273. }
  274. /**
  275. * Gets the display value of the "CC" line of the outlook message.
  276. * If there are multiple recipients, they will be separated
  277. * by semicolons.
  278. * This is not the actual list of addresses/values that will be
  279. * sent to if you click Reply in the email - those are stored
  280. * in {@link RecipientChunks}.
  281. * @throws ChunkNotFoundException If the cc-chunk does not exist and
  282. * returnNullOnMissingChunk is set
  283. */
  284. public String getDisplayCC() throws ChunkNotFoundException {
  285. return getStringFromChunk(mainChunks.getDisplayCCChunk());
  286. }
  287. /**
  288. * Gets the display value of the "BCC" line of the outlook message.
  289. * If there are multiple recipients, they will be separated
  290. * by semicolons.
  291. * This is not the actual list of addresses/values that will be
  292. * sent to if you click Reply in the email - those are stored
  293. * in {@link RecipientChunks}.
  294. * This will only be present in sent emails, not received ones!
  295. * @throws ChunkNotFoundException If the bcc-chunk does not exist and
  296. * returnNullOnMissingChunk is set
  297. */
  298. public String getDisplayBCC() throws ChunkNotFoundException {
  299. return getStringFromChunk(mainChunks.getDisplayBCCChunk());
  300. }
  301. /**
  302. * Returns all the recipients' email address, separated by
  303. * semicolons. Checks all the likely chunks in search of
  304. * the addresses.
  305. */
  306. public String getRecipientEmailAddress() throws ChunkNotFoundException {
  307. return toSemicolonList(getRecipientEmailAddressList());
  308. }
  309. /**
  310. * Returns an array of all the recipient's email address, normally
  311. * in TO then CC then BCC order.
  312. * Checks all the likely chunks in search of the addresses.
  313. */
  314. public String[] getRecipientEmailAddressList() throws ChunkNotFoundException {
  315. if(recipientChunks == null || recipientChunks.length == 0) {
  316. throw new ChunkNotFoundException("No recipients section present");
  317. }
  318. String[] emails = new String[recipientChunks.length];
  319. for(int i=0; i<emails.length; i++) {
  320. RecipientChunks rc = recipientChunks[i];
  321. String email = rc.getRecipientEmailAddress();
  322. if(email != null) {
  323. emails[i] = email;
  324. } else {
  325. if(returnNullOnMissingChunk) {
  326. emails[i] = null;
  327. } else {
  328. throw new ChunkNotFoundException("No email address holding chunks found for the " + (i+1) + "th recipient");
  329. }
  330. }
  331. }
  332. return emails;
  333. }
  334. /**
  335. * Returns all the recipients' names, separated by
  336. * semicolons. Checks all the likely chunks in search of
  337. * the names.
  338. * See also {@link #getDisplayTo()}, {@link #getDisplayCC()}
  339. * and {@link #getDisplayBCC()}.
  340. */
  341. public String getRecipientNames() throws ChunkNotFoundException {
  342. return toSemicolonList(getRecipientNamesList());
  343. }
  344. /**
  345. * Returns an array of all the recipient's names, normally
  346. * in TO then CC then BCC order.
  347. * Checks all the likely chunks in search of the names.
  348. * See also {@link #getDisplayTo()}, {@link #getDisplayCC()}
  349. * and {@link #getDisplayBCC()}.
  350. */
  351. public String[] getRecipientNamesList() throws ChunkNotFoundException {
  352. if(recipientChunks == null || recipientChunks.length == 0) {
  353. throw new ChunkNotFoundException("No recipients section present");
  354. }
  355. String[] names = new String[recipientChunks.length];
  356. for(int i=0; i<names.length; i++) {
  357. RecipientChunks rc = recipientChunks[i];
  358. String name = rc.getRecipientName();
  359. if(name != null) {
  360. names[i] = name;
  361. } else {
  362. throw new ChunkNotFoundException("No display name holding chunks found for the " + (i+1) + "th recipient");
  363. }
  364. }
  365. return names;
  366. }
  367. /**
  368. * Tries to identify the correct encoding for 7-bit (non-unicode)
  369. * strings in the file.
  370. * <p>Many messages store their strings as unicode, which is
  371. * nice and easy. Some use one-byte encodings for their
  372. * strings, but don't always store the encoding anywhere
  373. * helpful in the file.</p>
  374. * <p>This method checks for codepage properties, and failing that
  375. * looks at the headers for the message, and uses these to
  376. * guess the correct encoding for your file.</p>
  377. * <p>Bug #49441 has more on why this is needed</p>
  378. */
  379. public void guess7BitEncoding() {
  380. String generalcodepage = null;
  381. String htmlbodycodepage = null;
  382. String bodycodepage = null;
  383. //
  384. // General codepage: Message codepage property.
  385. //
  386. List<PropertyValue> val = mainChunks.getProperties().get(MAPIProperty.MESSAGE_CODEPAGE);
  387. if (val != null && val.size() > 0) {
  388. int codepage = ((LongPropertyValue) val.get(0)).getValue();
  389. try {
  390. String encoding = CodePageUtil.codepageToEncoding(codepage, true);
  391. generalcodepage = encoding;
  392. } catch (UnsupportedEncodingException e) {
  393. LOG.atWarn().log("Invalid codepage ID {} set for the message via {}, ignoring", box(codepage), MAPIProperty.MESSAGE_CODEPAGE);
  394. }
  395. }
  396. //
  397. // General codepage fallback: Message locale ID property.
  398. //
  399. if (generalcodepage == null) {
  400. val = mainChunks.getProperties().get(MAPIProperty.MESSAGE_LOCALE_ID);
  401. if (val != null && val.size() > 0) {
  402. int lcid = ((LongPropertyValue) val.get(0)).getValue();
  403. int codepage = LocaleUtil.getDefaultCodePageFromLCID(lcid);
  404. try {
  405. if (codepage != 0) {
  406. String encoding = CodePageUtil.codepageToEncoding(codepage, true);
  407. generalcodepage = encoding;
  408. }
  409. } catch (UnsupportedEncodingException e) {
  410. LOG.atWarn().log("Invalid codepage ID {}from locale ID{} set for the message via {}, ignoring", box(codepage),box(lcid), MAPIProperty.MESSAGE_LOCALE_ID);
  411. }
  412. }
  413. }
  414. //
  415. // General codepage fallback: Charset on a content type header.
  416. //
  417. if (generalcodepage == null) {
  418. try {
  419. String[] headers = getHeaders();
  420. if (headers != null && headers.length > 0) {
  421. Pattern p = Pattern.compile("content-type:.*?charset=[\"']?([^;'\"]+)[\"']?", Pattern.CASE_INSENSITIVE);
  422. for (String header : headers) {
  423. if (header.toLowerCase(LocaleUtil.getUserLocale()).startsWith("content-type")) {
  424. Matcher m = p.matcher(header);
  425. if (m.matches()) {
  426. String encoding = m.group(1);
  427. generalcodepage = encoding;
  428. }
  429. }
  430. }
  431. }
  432. } catch (ChunkNotFoundException e) {
  433. }
  434. }
  435. //
  436. // HTML and text body encoding: Internet CPID property.
  437. // UTF-8 is ignored for text body. This seems to be a special Outlook behavior.
  438. //
  439. val = mainChunks.getProperties().get(MAPIProperty.INTERNET_CPID);
  440. if (val != null && val.size() > 0) {
  441. int codepage = ((LongPropertyValue) val.get(0)).getValue();
  442. try {
  443. String encoding = CodePageUtil.codepageToEncoding(codepage, true);
  444. htmlbodycodepage = encoding;
  445. if (!encoding.equalsIgnoreCase("utf-8")) {
  446. bodycodepage = encoding;
  447. }
  448. } catch (UnsupportedEncodingException e) {
  449. LOG.atWarn().log("Invalid codepage ID {} set for the message via {}, ignoring", box(codepage), MAPIProperty.INTERNET_CPID);
  450. }
  451. }
  452. //
  453. // Apply encoding
  454. //
  455. set7BitEncoding(generalcodepage, htmlbodycodepage, bodycodepage);
  456. }
  457. /**
  458. * Many messages store their strings as unicode, which is
  459. * nice and easy. Some use one-byte encodings for their
  460. * strings, but don't easily store the encoding anywhere
  461. * in the file!
  462. * If you know what the encoding is of your file, you can
  463. * use this method to set the 7 bit encoding for all
  464. * the non unicode strings in the file.
  465. * @see #guess7BitEncoding()
  466. */
  467. public void set7BitEncoding(String charset) {
  468. set7BitEncoding(charset, charset, charset);
  469. }
  470. public void set7BitEncoding(String generalcharset, String htmlbodycharset, String bodycharset) {
  471. for(Chunk c : mainChunks.getChunks()) {
  472. if(c instanceof StringChunk) {
  473. if (c.getChunkId() == MAPIProperty.BODY_HTML.id) {
  474. if (htmlbodycharset != null) {
  475. ((StringChunk)c).set7BitEncoding(htmlbodycharset);
  476. }
  477. }
  478. else if (c.getChunkId() == MAPIProperty.BODY.id) {
  479. if (bodycharset != null) {
  480. ((StringChunk)c).set7BitEncoding(bodycharset);
  481. }
  482. }
  483. else if (generalcharset != null) {
  484. ((StringChunk)c).set7BitEncoding(generalcharset);
  485. }
  486. }
  487. }
  488. if (generalcharset != null) {
  489. if (nameIdChunks!=null) {
  490. for(Chunk c : nameIdChunks.getChunks()) {
  491. if(c instanceof StringChunk) {
  492. ((StringChunk)c).set7BitEncoding(generalcharset);
  493. }
  494. }
  495. }
  496. for(RecipientChunks rc : recipientChunks) {
  497. for(Chunk c : rc.getAll()) {
  498. if(c instanceof StringChunk) {
  499. ((StringChunk)c).set7BitEncoding(generalcharset);
  500. }
  501. }
  502. }
  503. }
  504. }
  505. /**
  506. * Does this file contain any strings that
  507. * are stored as 7 bit rather than unicode?
  508. */
  509. public boolean has7BitEncodingStrings() {
  510. for(Chunk c : mainChunks.getChunks()) {
  511. if(c instanceof StringChunk) {
  512. if( c.getType() == Types.ASCII_STRING ) {
  513. return true;
  514. }
  515. }
  516. }
  517. if (nameIdChunks!=null) {
  518. for(Chunk c : nameIdChunks.getChunks()) {
  519. if(c instanceof StringChunk) {
  520. if( c.getType() == Types.ASCII_STRING ) {
  521. return true;
  522. }
  523. }
  524. }
  525. }
  526. for(RecipientChunks rc : recipientChunks) {
  527. for(Chunk c : rc.getAll()) {
  528. if(c instanceof StringChunk) {
  529. if( c.getType() == Types.ASCII_STRING ) {
  530. return true;
  531. }
  532. }
  533. }
  534. }
  535. return false;
  536. }
  537. /**
  538. * Returns all the headers, one entry per line
  539. */
  540. public String[] getHeaders() throws ChunkNotFoundException {
  541. String headers = getStringFromChunk(mainChunks.getMessageHeaders());
  542. if(headers == null) {
  543. return null;
  544. }
  545. return headers.split("\\r?\\n");
  546. }
  547. /**
  548. * Gets the conversation topic of the parsed Outlook Message.
  549. * This is the part of the subject line that is after the RE: and FWD:
  550. * @throws ChunkNotFoundException If the conversation-topic chunk does not exist and
  551. * returnNullOnMissingChunk is set
  552. */
  553. public String getConversationTopic() throws ChunkNotFoundException {
  554. return getStringFromChunk(mainChunks.getConversationTopic());
  555. }
  556. /**
  557. * Gets the message class of the parsed Outlook Message.
  558. * (Yes, you can use this to determine if a message is a calendar
  559. * item, note, or actual outlook Message)
  560. * For emails the class will be IPM.Note
  561. *
  562. * @throws ChunkNotFoundException If the message-class chunk does not exist and
  563. * returnNullOnMissingChunk is set
  564. */
  565. public MESSAGE_CLASS getMessageClassEnum() throws ChunkNotFoundException {
  566. String mc = getStringFromChunk(mainChunks.getMessageClass());
  567. if (mc == null || mc.trim().length() == 0) {
  568. return MESSAGE_CLASS.UNSPECIFIED;
  569. } else if (mc.equalsIgnoreCase("IPM.Note")) {
  570. return MESSAGE_CLASS.NOTE;
  571. } else if (mc.equalsIgnoreCase("IPM.Contact")) {
  572. return MESSAGE_CLASS.CONTACT;
  573. } else if (mc.equalsIgnoreCase("IPM.Appointment")) {
  574. return MESSAGE_CLASS.APPOINTMENT;
  575. } else if (mc.equalsIgnoreCase("IPM.StickyNote")) {
  576. return MESSAGE_CLASS.STICKY_NOTE;
  577. } else if (mc.equalsIgnoreCase("IPM.Task")) {
  578. return MESSAGE_CLASS.TASK;
  579. } else if (mc.equalsIgnoreCase("IPM.Post")) {
  580. return MESSAGE_CLASS.POST;
  581. } else {
  582. LOG.atWarn().log("I don't recognize message class '{}'. Please open an issue on POI's bugzilla", mc);
  583. return MESSAGE_CLASS.UNKNOWN;
  584. }
  585. }
  586. /**
  587. * Gets the date that the message was accepted by the
  588. * server on.
  589. */
  590. public Calendar getMessageDate() throws ChunkNotFoundException {
  591. if (mainChunks.getSubmissionChunk() != null) {
  592. return mainChunks.getSubmissionChunk().getAcceptedAtTime();
  593. }
  594. else {
  595. // Try a few likely suspects...
  596. for (MAPIProperty prop : new MAPIProperty[] {
  597. MAPIProperty.CLIENT_SUBMIT_TIME, MAPIProperty.LAST_MODIFICATION_TIME,
  598. MAPIProperty.CREATION_TIME
  599. }) {
  600. List<PropertyValue> val = mainChunks.getProperties().get(prop);
  601. if (val != null && val.size() > 0) {
  602. return ((TimePropertyValue)val.get(0)).getValue();
  603. }
  604. }
  605. }
  606. if(returnNullOnMissingChunk)
  607. return null;
  608. throw new ChunkNotFoundException();
  609. }
  610. /**
  611. * Gets the main, core details chunks
  612. */
  613. public Chunks getMainChunks() {
  614. return mainChunks;
  615. }
  616. /**
  617. * Gets all the recipient details chunks.
  618. * These will normally be in the order of:
  619. * * TO recipients, in the order returned by {@link #getDisplayTo()}
  620. * * CC recipients, in the order returned by {@link #getDisplayCC()}
  621. * * BCC recipients, in the order returned by {@link #getDisplayBCC()}
  622. */
  623. public RecipientChunks[] getRecipientDetailsChunks() {
  624. return recipientChunks;
  625. }
  626. /**
  627. * Gets the Name ID chunks, or
  628. * null if there aren't any
  629. */
  630. public NameIdChunks getNameIdChunks() {
  631. return nameIdChunks;
  632. }
  633. /**
  634. * Gets the message attachments.
  635. */
  636. public AttachmentChunks[] getAttachmentFiles() {
  637. return attachmentChunks;
  638. }
  639. /**
  640. * Will you get a null on a missing chunk, or a
  641. * {@link ChunkNotFoundException} (default is the
  642. * exception).
  643. */
  644. public boolean isReturnNullOnMissingChunk() {
  645. return returnNullOnMissingChunk;
  646. }
  647. /**
  648. * Sets whether on asking for a missing chunk,
  649. * you get back null or a {@link ChunkNotFoundException}
  650. * (default is the exception).
  651. */
  652. public void setReturnNullOnMissingChunk(boolean returnNullOnMissingChunk) {
  653. this.returnNullOnMissingChunk = returnNullOnMissingChunk;
  654. }
  655. private String toSemicolonList(String[] l) {
  656. StringBuilder list = new StringBuilder();
  657. boolean first = true;
  658. for(String s : l) {
  659. if(s == null) continue;
  660. if(first) {
  661. first = false;
  662. } else {
  663. list.append("; ");
  664. }
  665. list.append(s);
  666. }
  667. return list.toString();
  668. }
  669. }