ReceivedEmail.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
  2. // All rights reserved.
  3. //
  4. // Redistribution and use in source and binary forms, with or without
  5. // modification, are permitted provided that the following conditions are met:
  6. //
  7. // 1. Redistributions of source code must retain the above copyright notice,
  8. // this list of conditions and the following disclaimer.
  9. //
  10. // 2. Redistributions in binary form must reproduce the above copyright
  11. // notice, this list of conditions and the following disclaimer in the
  12. // documentation and/or other materials provided with the distribution.
  13. //
  14. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  18. // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. // POSSIBILITY OF SUCH DAMAGE.
  25. package com.fjhx.utils.mail;
  26. import jakarta.mail.*;
  27. import jakarta.mail.internet.MimeMessage;
  28. import jakarta.mail.internet.MimePart;
  29. import jakarta.mail.util.ByteArrayDataSource;
  30. import java.io.File;
  31. import java.io.IOException;
  32. import java.io.InputStream;
  33. import java.io.UnsupportedEncodingException;
  34. import java.nio.charset.StandardCharsets;
  35. import java.util.ArrayList;
  36. import java.util.Date;
  37. import java.util.List;
  38. import static jakarta.mail.Flags.Flag;
  39. /**
  40. * Received email.
  41. */
  42. public class ReceivedEmail extends CommonEmail<ReceivedEmail> {
  43. public static final ReceivedEmail[] EMPTY_ARRAY = new ReceivedEmail[0];
  44. /**
  45. * {@link List} of attached {@link ReceivedEmail}s.
  46. */
  47. private final List<ReceivedEmail> attachedMessages = new ArrayList<>();
  48. private File attachmentStorage;
  49. /**
  50. * {@link Message} for this {@link ReceivedEmail}.
  51. */
  52. private Message originalMessage;
  53. /**
  54. * {@link Flags} for this {@link ReceivedEmail}.
  55. */
  56. private Flags flags;
  57. private int messageNumber;
  58. private String messageId;
  59. private Date receivedDate;
  60. /**
  61. * Creates an empty {@link ReceivedEmail}.
  62. */
  63. private ReceivedEmail() {
  64. }
  65. /**
  66. * Creates a {@link ReceivedEmail} from a given {@link Message}.
  67. *
  68. * @param msg {@link Message}
  69. * @param envelope flag if this is an envelope
  70. */
  71. public ReceivedEmail(final Message msg, final boolean envelope, final File attachmentStorage) {
  72. this.attachmentStorage = attachmentStorage;
  73. this.originalMessage = msg;
  74. try {
  75. parseMessage(msg, envelope);
  76. } catch (final Exception ex) {
  77. throw new MailException("Message parsing failed", ex);
  78. }
  79. }
  80. /**
  81. * Static constructor for fluent interface.
  82. *
  83. * @return new {@link ReceivedEmail}.
  84. */
  85. public static ReceivedEmail create() {
  86. return new ReceivedEmail();
  87. }
  88. /**
  89. * Returns the Content-ID of this {@link Part}. Returns {@code null} if none present.
  90. *
  91. * @param part {@link Part} the Part to parse.
  92. * @return String containing content ID.
  93. * @throws MessagingException if there is a failure.
  94. * @see MimePart#getContentID()
  95. */
  96. protected static String parseContentId(final Part part) throws MessagingException {
  97. if (part instanceof MimePart) {
  98. final MimePart mp = (MimePart) part;
  99. return mp.getContentID();
  100. } else {
  101. return null;
  102. }
  103. }
  104. // ---------------------------------------------------------------- original message
  105. /**
  106. * Returns {@code true} if the {@link Part} is inline.
  107. *
  108. * @param part {@link Part} to parse.
  109. * @return {@code true} if the {@link Part} is inline.
  110. * @throws MessagingException if there is a failure.
  111. */
  112. protected static boolean parseInline(final Part part) throws MessagingException {
  113. if (part instanceof MimePart) {
  114. final String dispositionId = part.getDisposition();
  115. return dispositionId != null && dispositionId.equalsIgnoreCase("inline");
  116. }
  117. return false;
  118. }
  119. /**
  120. * Creates {@link EmailAttachmentBuilder} from {@link Part} and sets Content ID, inline and name.
  121. *
  122. * @param part {@link Part}.
  123. * @return this
  124. * @see #attachment(EmailAttachment)
  125. */
  126. private static EmailAttachmentBuilder addAttachmentInfo(final Part part) throws MessagingException {
  127. final String fileName = EmailUtil.resolveFileName(part);
  128. final String contentId = parseContentId(part);
  129. final boolean isInline = parseInline(part);
  130. return new EmailAttachmentBuilder()
  131. .name(fileName)
  132. .contentId(contentId)
  133. .inline(isInline);
  134. }
  135. @Override
  136. public ReceivedEmail clone() {
  137. return create()
  138. // original message
  139. .originalMessage(originalMessage())
  140. // flags
  141. .flags(flags())
  142. // message number and id
  143. .messageNumber(messageNumber())
  144. .messageId(messageId())
  145. // from / reply-to
  146. .from(from())
  147. .replyTo(replyTo())
  148. // recipients
  149. .to(to())
  150. .cc(cc())
  151. // subject
  152. .subject(subject(), subjectEncoding())
  153. // dates
  154. .receivedDate(receivedDate())
  155. .sentDate(sentDate())
  156. // headers - includes priority
  157. .headers(headers())
  158. // content / attachments
  159. .message(messages())
  160. .storeAttachments(attachments())
  161. .attachedMessages(attachedMessages());
  162. }
  163. // ---------------------------------------------------------------- flags
  164. /**
  165. * Parses {@link Message} and extracts all data for the received message.
  166. *
  167. * @param msg {@link Message} to parse.
  168. * @throws IOException if there is an error with the content
  169. * @throws MessagingException if there is an error.
  170. */
  171. protected void parseMessage(final Message msg, final boolean envelope) throws MessagingException, IOException {
  172. // flags
  173. flags(msg.getFlags());
  174. // message number
  175. messageNumber(msg.getMessageNumber());
  176. if (msg instanceof MimeMessage) {
  177. messageId(((MimeMessage) msg).getMessageID());
  178. }
  179. // single from
  180. final Address[] addresses = msg.getFrom();
  181. if (addresses != null && addresses.length > 0) {
  182. from(addresses[0]);
  183. }
  184. // reply-to
  185. replyTo(msg.getReplyTo());
  186. // recipients
  187. to(msg.getRecipients(Message.RecipientType.TO));
  188. cc(msg.getRecipients(Message.RecipientType.CC));
  189. // no BCC because this will always be empty
  190. // subject
  191. subject(msg.getSubject());
  192. // dates
  193. receivedDate(msg.getReceivedDate());
  194. sentDate(msg.getSentDate());
  195. // headers
  196. headers(msg.getAllHeaders());
  197. // content
  198. if (!envelope) {
  199. processPart(msg);
  200. }
  201. }
  202. /**
  203. * Process part of the received message. All parts are simply added to the {@link ReceivedEmail},
  204. * i.e. hierarchy is not saved.
  205. *
  206. * @param part {@link Part} of received message
  207. * @throws IOException if there is an error with the content.
  208. * @throws MessagingException if there is an error.
  209. */
  210. protected void processPart(final Part part) throws MessagingException, IOException {
  211. final Object content = part.getContent();
  212. if (content instanceof String) {
  213. addStringContent(part, (String) content);
  214. } else if (content instanceof Multipart) {
  215. processMultipart((Multipart) content);
  216. } else if (content instanceof InputStream) {
  217. addAttachment(part, (InputStream) content, attachmentStorage);
  218. } else if (content instanceof MimeMessage) {
  219. final MimeMessage mimeMessage = (MimeMessage) content;
  220. attachedMessage(new ReceivedEmail(mimeMessage, false, attachmentStorage));
  221. } else {
  222. addAttachment(part, part.getInputStream(), attachmentStorage);
  223. }
  224. }
  225. /**
  226. * Process the {@link Multipart}.
  227. *
  228. * @param mp {@link Multipart}
  229. * @throws MessagingException if there is a failure.
  230. * @throws IOException if there is an issue with the {@link Multipart}.
  231. */
  232. private void processMultipart(final Multipart mp) throws MessagingException, IOException {
  233. final int count = mp.getCount();
  234. for (int i = 0; i < count; i++) {
  235. final Part innerPart = mp.getBodyPart(i);
  236. processPart(innerPart);
  237. }
  238. }
  239. /**
  240. * Adds String content as either {@link EmailAttachment} or as {@link EmailMessage}.
  241. *
  242. * @param part {@link Part}
  243. * @param content Content as {@link String}
  244. * @throws MessagingException if there is a failure.
  245. * @throws UnsupportedEncodingException if the named charset is not supported.
  246. * @see #message(String, String, String)
  247. */
  248. private void addStringContent(final Part part, final String content) throws MessagingException, UnsupportedEncodingException {
  249. final String contentType = part.getContentType();
  250. final String encoding = EmailUtil.extractEncoding(contentType, StandardCharsets.US_ASCII.name());
  251. final String disposition = part.getDisposition();
  252. if (disposition != null && disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
  253. addAttachment(part, content.getBytes(encoding));
  254. } else {
  255. final String mimeType = EmailUtil.extractMimeType(contentType);
  256. message(content, mimeType, encoding);
  257. }
  258. }
  259. /**
  260. * @return {@link Message}
  261. */
  262. public Message originalMessage() {
  263. return originalMessage;
  264. }
  265. /**
  266. * Sets the original message.
  267. *
  268. * @param originalMessage {@link Message} to set.
  269. */
  270. public ReceivedEmail originalMessage(final Message originalMessage) {
  271. this.originalMessage = originalMessage;
  272. return this;
  273. }
  274. /**
  275. * @return {@link Flags}
  276. */
  277. public Flags flags() {
  278. return flags;
  279. }
  280. /**
  281. * Sets the flags.
  282. *
  283. * @param flags {@link Flags} to set.
  284. */
  285. public ReceivedEmail flags(final Flags flags) {
  286. this.flags = flags;
  287. return this;
  288. }
  289. /**
  290. * Returns {@code true} if message is answered.
  291. *
  292. * @return {@code true} if message is answered.
  293. */
  294. public boolean isAnswered() {
  295. return flags.contains(Flag.ANSWERED);
  296. }
  297. // ---------------------------------------------------------------- additional properties
  298. /**
  299. * Returns {@code true} if message is deleted.
  300. *
  301. * @return {@code true} if message is deleted.
  302. */
  303. public boolean isDeleted() {
  304. return flags.contains(Flag.DELETED);
  305. }
  306. /**
  307. * Returns {@code true} if message is draft.
  308. */
  309. public boolean isDraft() {
  310. return flags.contains(Flag.DRAFT);
  311. }
  312. /**
  313. * Returns {@code true} is message is flagged.
  314. *
  315. * @return {@code true} is message is flagged.
  316. */
  317. public boolean isFlagged() {
  318. return flags.contains(Flag.FLAGGED);
  319. }
  320. /**
  321. * Returns {@code true} if message is recent.
  322. *
  323. * @return {@code true} if message is recent.
  324. */
  325. public boolean isRecent() {
  326. return flags.contains(Flag.RECENT);
  327. }
  328. /**
  329. * Returns {@code true} if message is seen.
  330. *
  331. * @return {@code true} if message is seen.
  332. */
  333. public boolean isSeen() {
  334. return flags.contains(Flag.SEEN);
  335. }
  336. /**
  337. * Returns message number.
  338. *
  339. * @return message number
  340. */
  341. public int messageNumber() {
  342. return messageNumber;
  343. }
  344. /**
  345. * Returns message ID if set by server.
  346. */
  347. public String messageId() {
  348. return messageId;
  349. }
  350. /**
  351. * Sets message number.
  352. *
  353. * @param messageNumber The message number to set.
  354. * @return this
  355. */
  356. public ReceivedEmail messageNumber(final int messageNumber) {
  357. this.messageNumber = messageNumber;
  358. return this;
  359. }
  360. /**
  361. * Sets message ID.
  362. */
  363. public ReceivedEmail messageId(final String messageId) {
  364. this.messageId = messageId;
  365. return this;
  366. }
  367. // ---------------------------------------------------------------- attachments
  368. /**
  369. * Sets email's received {@link Date}.
  370. *
  371. * @param date The received {@link Date} to set.
  372. * @return this
  373. */
  374. public ReceivedEmail receivedDate(final Date date) {
  375. receivedDate = date;
  376. return this;
  377. }
  378. /**
  379. * Returns email's received {@link Date}.
  380. *
  381. * @return The email's received {@link Date}.
  382. */
  383. public Date receivedDate() {
  384. return receivedDate;
  385. }
  386. /**
  387. * Adds received attachment.
  388. *
  389. * @param part {@link Part}.
  390. * @param content Content as {@link InputStream}.
  391. * @return this
  392. * @see #attachment(EmailAttachment)
  393. */
  394. private ReceivedEmail addAttachment(final Part part, final InputStream content, final File attachmentStorage) throws MessagingException, IOException {
  395. final EmailAttachmentBuilder builder = addAttachmentInfo(part);
  396. builder.content(content, part.getContentType());
  397. if (attachmentStorage != null) {
  398. String name = messageId + "-" + (this.attachments().size() + 1);
  399. return storeAttachment(builder.buildFileDataSource(name, attachmentStorage));
  400. }
  401. return storeAttachment(builder.buildByteArrayDataSource());
  402. }
  403. // ---------------------------------------------------------------- inner messages
  404. /**
  405. * Adds received attachment.
  406. *
  407. * @param part {@link Part}.
  408. * @param content Content as byte array.
  409. * @return this
  410. * @see #attachment(EmailAttachment)
  411. */
  412. private ReceivedEmail addAttachment(final Part part, final byte[] content) throws MessagingException {
  413. final EmailAttachmentBuilder builder = addAttachmentInfo(part);
  414. builder.content(content, part.getContentType());
  415. final EmailAttachment<ByteArrayDataSource> attachment = builder.buildByteArrayDataSource();
  416. attachment.setSize(content.length);
  417. return storeAttachment(attachment);
  418. }
  419. /**
  420. * Adds attached {@link ReceivedEmail}s.
  421. *
  422. * @param emails {@link List} of {@link ReceivedEmail}s to attach.
  423. */
  424. public ReceivedEmail attachedMessages(final List<ReceivedEmail> emails) {
  425. attachedMessages.addAll(emails);
  426. return this;
  427. }
  428. /**
  429. * Adds attached {@link ReceivedEmail}.
  430. *
  431. * @param email {@link ReceivedEmail} to attach.
  432. * @return this
  433. */
  434. public ReceivedEmail attachedMessage(final ReceivedEmail email) {
  435. attachedMessages.add(email);
  436. return this;
  437. }
  438. /**
  439. * Returns the {@link List} of attached messages.
  440. * If no attached message is available, returns an empty {@link List}.
  441. *
  442. * @return {@link List} of {@link ReceivedEmail}s.
  443. */
  444. public List<ReceivedEmail> attachedMessages() {
  445. return attachedMessages;
  446. }
  447. }