EmailUtil.java 11 KB

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