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.

OutlookTextExtractor.java 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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.extractor;
  16. import static org.apache.poi.util.StringUtil.startsWithIgnoreCase;
  17. import java.io.File;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.text.SimpleDateFormat;
  21. import java.util.Arrays;
  22. import java.util.Collections;
  23. import java.util.Date;
  24. import java.util.Iterator;
  25. import java.util.Locale;
  26. import org.apache.poi.extractor.POIOLE2TextExtractor;
  27. import org.apache.poi.hsmf.MAPIMessage;
  28. import org.apache.poi.hsmf.datatypes.AttachmentChunks;
  29. import org.apache.poi.hsmf.datatypes.StringChunk;
  30. import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
  31. import org.apache.poi.poifs.filesystem.DirectoryNode;
  32. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  33. import org.apache.poi.util.LocaleUtil;
  34. /**
  35. * A text extractor for HSMF (Outlook) .msg files.
  36. * Outputs in a format somewhat like a plain text email.
  37. *
  38. * @since 4.1.2
  39. */
  40. public class OutlookTextExtractor implements POIOLE2TextExtractor {
  41. private final MAPIMessage msg;
  42. private boolean doCloseFilesystem = true;
  43. public OutlookTextExtractor(MAPIMessage msg) {
  44. this.msg = msg;
  45. }
  46. public OutlookTextExtractor(DirectoryNode poifsDir) throws IOException {
  47. this(new MAPIMessage(poifsDir));
  48. }
  49. public OutlookTextExtractor(POIFSFileSystem fs) throws IOException {
  50. this(new MAPIMessage(fs));
  51. }
  52. public OutlookTextExtractor(InputStream inp) throws IOException {
  53. this(new MAPIMessage(inp));
  54. }
  55. public static void main(String[] args) throws Exception {
  56. if(args.length == 0) {
  57. System.err.println("Usage: OutlookTextExtractor <file> [<file> ...]");
  58. System.exit(1);
  59. }
  60. for (String filename : args) {
  61. try (POIFSFileSystem poifs = new POIFSFileSystem(new File(filename));
  62. OutlookTextExtractor extractor = new OutlookTextExtractor(poifs)) {
  63. System.out.println(extractor.getText());
  64. }
  65. }
  66. }
  67. /**
  68. * Returns the underlying MAPI message
  69. */
  70. public MAPIMessage getMAPIMessage() {
  71. return msg;
  72. }
  73. /**
  74. * Outputs something a little like a RFC822 email
  75. */
  76. public String getText() {
  77. StringBuilder s = new StringBuilder();
  78. // See if we can get a suitable encoding for any
  79. // non unicode text in the file
  80. msg.guess7BitEncoding();
  81. // Off we go
  82. Iterator<String> emails;
  83. try {
  84. emails = Arrays.asList(msg.getRecipientEmailAddressList()).iterator();
  85. } catch (ChunkNotFoundException e) {
  86. emails = Collections.emptyIterator();
  87. }
  88. try {
  89. s.append("From: ").append(msg.getDisplayFrom()).append("\n");
  90. } catch (ChunkNotFoundException ignored) {
  91. }
  92. // For To, CC and BCC, try to match the names
  93. // up with their email addresses. Relies on the
  94. // Recipient Chunks being in the same order as
  95. // people in To + CC + BCC.
  96. try {
  97. handleEmails(s, "To", msg.getDisplayTo(), emails);
  98. } catch (ChunkNotFoundException ignored) {
  99. }
  100. try {
  101. handleEmails(s, "CC", msg.getDisplayCC(), emails);
  102. } catch (ChunkNotFoundException ignored) {
  103. }
  104. try {
  105. handleEmails(s, "BCC", msg.getDisplayBCC(), emails);
  106. } catch (ChunkNotFoundException ignored) {
  107. }
  108. // Date - try two ways to find it
  109. try {
  110. // First try via the proper chunk
  111. SimpleDateFormat f = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss Z", Locale.ROOT);
  112. f.setTimeZone(LocaleUtil.getUserTimeZone());
  113. s.append("Date: ").append(f.format(msg.getMessageDate() == null ? new Date(0) : msg.getMessageDate().getTime())).append("\n");
  114. } catch (ChunkNotFoundException e) {
  115. try {
  116. // Failing that try via the raw headers
  117. String[] headers = msg.getHeaders();
  118. for (String header : headers) {
  119. if (startsWithIgnoreCase(header, "date:")) {
  120. s.append("Date:").append(header, header.indexOf(':') + 1, header.length()).append("\n");
  121. break;
  122. }
  123. }
  124. } catch (ChunkNotFoundException he) {
  125. // We can't find the date, sorry...
  126. }
  127. }
  128. try {
  129. s.append("Subject: ").append(msg.getSubject()).append("\n");
  130. } catch (ChunkNotFoundException ignored) {
  131. }
  132. // Display attachment names
  133. // To get the attachments, use ExtractorFactory
  134. for (AttachmentChunks att : msg.getAttachmentFiles()) {
  135. StringChunk name = att.getAttachLongFileName();
  136. if (name == null) name = att.getAttachFileName();
  137. String attName = name == null ? null : name.getValue();
  138. if (att.getAttachMimeTag() != null &&
  139. att.getAttachMimeTag().getValue() != null) {
  140. attName = att.getAttachMimeTag().getValue() + " = " + attName;
  141. }
  142. s.append("Attachment: ").append(attName).append("\n");
  143. }
  144. try {
  145. s.append("\n").append(msg.getTextBody()).append("\n");
  146. } catch (ChunkNotFoundException ignored) {
  147. }
  148. return s.toString();
  149. }
  150. /**
  151. * Takes a Display focused string, eg "Nick; Jim" and an iterator
  152. * of emails, and does its best to return something like
  153. * {@code "Nick <nick@example.com>; Jim <jim@example.com>"}
  154. */
  155. protected void handleEmails(StringBuilder s, String type, String displayText, Iterator<String> emails) {
  156. if (displayText == null || displayText.length() == 0) {
  157. return;
  158. }
  159. String[] names = displayText.split(";\\s*");
  160. boolean first = true;
  161. s.append(type).append(": ");
  162. for (String name : names) {
  163. if (first) {
  164. first = false;
  165. } else {
  166. s.append("; ");
  167. }
  168. s.append(name);
  169. if (emails.hasNext()) {
  170. String email = emails.next();
  171. // Append the email address in <>, assuming
  172. // the name wasn't already the email address
  173. if (!email.equals(name)) {
  174. s.append(" <").append(email).append(">");
  175. }
  176. }
  177. }
  178. s.append("\n");
  179. }
  180. @Override
  181. public MAPIMessage getDocument() {
  182. return msg;
  183. }
  184. @Override
  185. public void setCloseFilesystem(boolean doCloseFilesystem) {
  186. this.doCloseFilesystem = doCloseFilesystem;
  187. }
  188. @Override
  189. public boolean isCloseFilesystem() {
  190. return doCloseFilesystem;
  191. }
  192. @Override
  193. public MAPIMessage getFilesystem() {
  194. return msg;
  195. }
  196. }