EmailUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. package com.simuwang.base.common.util;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.exceptions.ExceptionUtil;
  5. import cn.hutool.core.map.MapUtil;
  6. import cn.hutool.core.util.StrUtil;
  7. import cn.hutool.extra.mail.JakartaUserPassAuthenticator;
  8. import com.simuwang.base.common.conts.DateConst;
  9. import com.simuwang.base.pojo.dto.EmailContentInfoDTO;
  10. import com.simuwang.base.pojo.dto.MailboxInfoDTO;
  11. import com.sun.mail.imap.IMAPStore;
  12. import jakarta.mail.Message;
  13. import jakarta.mail.MessagingException;
  14. import jakarta.mail.Session;
  15. import jakarta.mail.Store;
  16. import jakarta.mail.internet.MimeBodyPart;
  17. import jakarta.mail.internet.MimeMultipart;
  18. import jakarta.mail.internet.MimeUtility;
  19. import org.apache.commons.io.FileUtils;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import java.io.File;
  23. import java.util.*;
  24. /**
  25. * @author mozuwen
  26. * @date 2024-09-04
  27. * @description 邮件解析工具
  28. */
  29. public class EmailUtil {
  30. private static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);
  31. private static final String POP3 = "pop3";
  32. private static final String IMAP = "imap";
  33. /**
  34. * 采集邮件(多消息体)信息
  35. *
  36. * @param message 邮件
  37. * @param emailAddress 邮箱地址
  38. * @param path 存储路径
  39. * @return 从邮箱采集到的信息
  40. * @throws Exception 异常信息
  41. */
  42. public static List<EmailContentInfoDTO> collectMimeMultipart(Message message, String emailAddress, String path) throws Exception {
  43. List<EmailContentInfoDTO> emailContentInfoDTOList = CollUtil.newArrayList();
  44. String emailTitle = message.getSubject();
  45. String emailDate = DateUtil.format(message.getSentDate(), DateConst.YYYYMMDDHHMMSS24);
  46. String emailDateStr = DateUtil.format(message.getSentDate(), DateConst.YYYYMMDD);
  47. String filePath = path + "/" + emailAddress + "/" + emailDateStr + "/";
  48. MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
  49. int length = mimeMultipart.getCount();
  50. // 遍历邮件消息体
  51. for (int i = 0; i < length; i++) {
  52. EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  53. MimeBodyPart part = (MimeBodyPart) mimeMultipart.getBodyPart(i);
  54. Object partContent = part.getContent();
  55. String contentClass = part.getContent().getClass().getSimpleName();
  56. // 1.邮件正文
  57. if ("String".equals(contentClass)) {
  58. // 文件名 = 邮件主题 + 邮件日期
  59. String fileName = emailTitle + "_" + emailDate + ".html";
  60. emailContentInfoDTO = collectTextPart(part, partContent, filePath, fileName);
  61. } else if ("BASE64DecoderStream".equals(contentClass)) {
  62. if (StrUtil.isNotBlank(part.getFileName())) {
  63. String fileName = MimeUtility.decodeText(part.getFileName());
  64. emailContentInfoDTO.setFileName(fileName);
  65. File savefile = new File(filePath + fileName);
  66. if (!savefile.exists()) {
  67. if (!savefile.getParentFile().exists()) {
  68. savefile.getParentFile().mkdirs();
  69. }
  70. FileUtil.saveFile(savefile, part);
  71. } else {
  72. FileUtils.deleteQuietly(savefile);
  73. FileUtil.saveFile(savefile, part);
  74. }
  75. emailContentInfoDTO.setFilePath(filePath + fileName);
  76. }
  77. } else if ("MimeMultipart".equals(contentClass)) {
  78. MimeMultipart contentPart = (MimeMultipart) partContent;
  79. int length2 = contentPart.getCount();
  80. for (int i2 = 0; i2 < length2; i2++) {
  81. part = (MimeBodyPart) contentPart.getBodyPart(i2);
  82. partContent = part.getContent();
  83. contentClass = partContent.getClass().getSimpleName();
  84. if ("String".equals(contentClass)) {
  85. // 文件名 = 邮件主题 + 邮件日期
  86. String fileName = emailTitle + "_" + emailDate + ".html";
  87. emailContentInfoDTO = collectTextPart(part, partContent, filePath, fileName);
  88. }
  89. }
  90. }
  91. if (emailContentInfoDTO.getEmailContent() == null && emailContentInfoDTO.getFilePath() == null) {
  92. continue;
  93. }
  94. emailContentInfoDTO.setEmailAddress(emailAddress);
  95. emailContentInfoDTO.setEmailTitle(emailTitle);
  96. emailContentInfoDTO.setEmailDate(DateUtil.format(message.getSentDate(), DateConst.YYYY_MM_DD_HH_MM_SS));
  97. emailContentInfoDTOList.add(emailContentInfoDTO);
  98. }
  99. return emailContentInfoDTOList;
  100. }
  101. /**
  102. * 根据日期过滤邮件
  103. *
  104. * @param messages 采集到的邮件
  105. * @param startDate 邮件起始日期
  106. * @param endDate 邮件截止日期
  107. * @return 符合日期的邮件
  108. */
  109. public static List<Message> filterMessage(Message[] messages, Date startDate, Date endDate) {
  110. long startTime = System.currentTimeMillis();
  111. List<Message> messageList = CollUtil.newArrayList();
  112. if (messages == null) {
  113. return messageList;
  114. }
  115. for (Message message : messages) {
  116. try {
  117. if (message.getSentDate().compareTo(startDate) >= 0 && message.getSentDate().compareTo(endDate) <= 0) {
  118. messageList.add(message);
  119. }
  120. } catch (MessagingException e) {
  121. throw new RuntimeException(e);
  122. }
  123. }
  124. logger.info("根据日期过滤邮件耗时 -> {}ms", (System.currentTimeMillis() - startTime));
  125. return messageList;
  126. }
  127. /**
  128. * 采集邮件正文
  129. *
  130. * @param part 邮件消息体
  131. * @param partContent 邮件消息内筒
  132. * @param filePath 文件路径
  133. * @param fileName 文件名
  134. * @return 采集到邮件正文(html格式包含table标签)
  135. */
  136. public static EmailContentInfoDTO collectTextPart(MimeBodyPart part, Object partContent, String filePath, String fileName) {
  137. EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  138. try {
  139. if ((part.getContentType().contains("text/html") || part.getContentType().contains("TEXT/HTML"))) {
  140. if (partContent.toString().contains("<table")) {
  141. emailContentInfoDTO.setEmailContent(partContent.toString());
  142. String savePath = filePath + fileName;
  143. File saveFile = new File(savePath);
  144. if (!saveFile.exists()) {
  145. if (!saveFile.getParentFile().exists()) {
  146. saveFile.getParentFile().mkdirs();
  147. saveFile.getParentFile().setExecutable(true);
  148. }
  149. FileUtil.writeFile(savePath, partContent.toString());
  150. }
  151. emailContentInfoDTO.setFileName(fileName);
  152. emailContentInfoDTO.setFilePath(savePath);
  153. }
  154. }
  155. } catch (MessagingException e) {
  156. logger.info("邮件正文采集失败 -> 文件名:{}, 报错堆栈:{}", fileName, ExceptionUtil.stacktraceToString(e));
  157. return emailContentInfoDTO;
  158. }
  159. return emailContentInfoDTO;
  160. }
  161. /**
  162. * 判断邮件是否符合解析条件
  163. *
  164. * @param subject 邮件主题
  165. * @param emailTypeMap 邮件类型识别规则映射表
  166. * @return 邮件类型:1-净值,2-估值表,3-定期报告,null代表不支持该邮件解析
  167. */
  168. public static Integer getEmailTypeBySubject(String subject, Map<Integer, List<String>> emailTypeMap) {
  169. if (MapUtil.isEmpty(emailTypeMap)) {
  170. return null;
  171. }
  172. for (Map.Entry<Integer, List<String>> emailTypeEntry : emailTypeMap.entrySet()) {
  173. for (String field : emailTypeEntry.getValue()) {
  174. if (subject.contains(field)) {
  175. return emailTypeEntry.getKey();
  176. }
  177. }
  178. }
  179. return null;
  180. }
  181. public static Store getStoreNew(MailboxInfoDTO mailboxInfoDTO) {
  182. // 配置连接邮件服务器参数
  183. Properties props = getMailProps(mailboxInfoDTO);
  184. // 创建Session实例对象
  185. Session session = Session.getInstance(props, new JakartaUserPassAuthenticator(mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword()));
  186. Store store;
  187. try {
  188. String protocol = mailboxInfoDTO.getProtocol().equals(IMAP) ? "imaps" : "pop3";
  189. if (mailboxInfoDTO.getProtocol().contains(IMAP)) {
  190. IMAPStore imapStore = (IMAPStore) session.getStore(protocol);
  191. imapStore.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  192. // 网易邮箱需要带上身份标识,详情请看:https://www.hmail163.com/content/?404.html
  193. Map<String, String> clientParams = new HashMap<>(2);
  194. clientParams.put("name", "my-imap");
  195. clientParams.put("version", "1.0");
  196. imapStore.id(clientParams);
  197. return imapStore;
  198. } else {
  199. store = session.getStore(protocol);
  200. store.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  201. return store;
  202. }
  203. } catch (Exception e) {
  204. logger.error("邮箱信息:{},服务器参数:{}", mailboxInfoDTO, props);
  205. logger.error("连接邮箱报错堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  206. return null;
  207. }
  208. }
  209. public static Properties getMailProps(MailboxInfoDTO mailboxInfoDTO) {
  210. Properties props = new Properties();
  211. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(POP3)) {
  212. props.put("mail.pop3.host", mailboxInfoDTO.getHost());
  213. props.put("mail.pop3.user", mailboxInfoDTO.getAccount());
  214. props.put("mail.pop3.socketFactory", mailboxInfoDTO.getPort());
  215. props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  216. props.put("mail.pop3.port", mailboxInfoDTO.getPort());
  217. props.put("mail.store.protocol", mailboxInfoDTO.getProtocol());
  218. }
  219. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(IMAP)) {
  220. props.put("mail.store.protocol", "imaps");
  221. props.put("mail.imap.host", mailboxInfoDTO.getHost());
  222. props.put("mail.imap.port", mailboxInfoDTO.getPort());
  223. props.put("mail.imaps.ssl.enable", "true");
  224. props.put("mail.imaps.ssl.trust", "*");
  225. props.put("mail.imap.auth", "true");
  226. props.put("mail.imap.starttls.enable", "true");
  227. props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  228. props.put("mail.imap.socketFactory.fallback", "false");
  229. }
  230. return props;
  231. }
  232. }