EmailUtil.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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.activation.DataHandler;
  14. import jakarta.mail.*;
  15. import jakarta.mail.internet.*;
  16. import jakarta.mail.util.ByteArrayDataSource;
  17. import org.apache.commons.io.FileUtils;
  18. import org.apache.commons.lang3.StringUtils;
  19. import org.slf4j.Logger;
  20. import org.slf4j.LoggerFactory;
  21. import org.springframework.mail.javamail.JavaMailSender;
  22. import java.io.File;
  23. import java.nio.file.Files;
  24. import java.nio.file.Paths;
  25. import java.util.*;
  26. /**
  27. * @author mozuwen
  28. * @date 2024-09-04
  29. * @description 邮件解析工具
  30. */
  31. public class EmailUtil {
  32. private static final Logger logger = LoggerFactory.getLogger(EmailUtil.class);
  33. private static final String POP3 = "pop3";
  34. private static final String IMAP = "imap";
  35. /**
  36. * 采集邮件(多消息体)信息
  37. *
  38. * @param message 邮件
  39. * @param emailAddress 邮箱地址
  40. * @param path 存储路径
  41. * @return 从邮箱采集到的信息
  42. * @throws Exception 异常信息
  43. */
  44. public static List<EmailContentInfoDTO> collectMimeMultipart(Message message, String emailAddress, String path) throws Exception {
  45. List<EmailContentInfoDTO> emailContentInfoDTOList = CollUtil.newArrayList();
  46. String emailTitle = message.getSubject();
  47. String emailDate = DateUtil.format(message.getSentDate(), DateConst.YYYYMMDDHHMMSS24);
  48. String emailDateStr = DateUtil.format(message.getSentDate(), DateConst.YYYYMMDD);
  49. String filePath = path + "/" + emailAddress + "/" + emailDateStr + "/";
  50. MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
  51. int length = mimeMultipart.getCount();
  52. // 遍历邮件消息体
  53. for (int i = 0; i < length; i++) {
  54. EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  55. MimeBodyPart part = (MimeBodyPart) mimeMultipart.getBodyPart(i);
  56. Object partContent = part.getContent();
  57. String contentClass = part.getContent().getClass().getSimpleName();
  58. // 1.邮件正文
  59. if ("String".equals(contentClass)) {
  60. // 文件名 = 邮件主题 + 邮件日期
  61. String fileName = emailTitle + "_" + emailDate + ".html";
  62. emailContentInfoDTO = collectTextPart(part, partContent, filePath, fileName);
  63. } else if ("BASE64DecoderStream".equals(contentClass)) {
  64. if (StrUtil.isNotBlank(part.getFileName())) {
  65. String fileName = MimeUtility.decodeText(part.getFileName());
  66. if (!isSupportedFileType(fileName)) {
  67. continue;
  68. }
  69. emailContentInfoDTO.setFileName(fileName);
  70. String realPath = filePath + emailDate + fileName;
  71. File saveFile = new File(realPath);
  72. if (!saveFile.exists()) {
  73. if (!saveFile.getParentFile().exists()) {
  74. saveFile.getParentFile().mkdirs();
  75. }
  76. FileUtil.saveFile(saveFile, part);
  77. } else {
  78. FileUtils.deleteQuietly(saveFile);
  79. FileUtil.saveFile(saveFile, part);
  80. }
  81. emailContentInfoDTO.setFilePath(realPath);
  82. }
  83. } else if ("MimeMultipart".equals(contentClass)) {
  84. MimeMultipart contentPart = (MimeMultipart) partContent;
  85. int length2 = contentPart.getCount();
  86. for (int i2 = 0; i2 < length2; i2++) {
  87. part = (MimeBodyPart) contentPart.getBodyPart(i2);
  88. partContent = part.getContent();
  89. contentClass = partContent.getClass().getSimpleName();
  90. if ("String".equals(contentClass)) {
  91. // 文件名 = 邮件主题 + 邮件日期
  92. String fileName = emailTitle + "_" + emailDate + ".html";
  93. emailContentInfoDTO = collectTextPart(part, partContent, filePath, fileName);
  94. }
  95. }
  96. }
  97. if (emailContentInfoDTO.getEmailContent() == null && emailContentInfoDTO.getFilePath() == null) {
  98. continue;
  99. }
  100. emailContentInfoDTO.setEmailAddress(emailAddress);
  101. emailContentInfoDTO.setEmailTitle(emailTitle);
  102. emailContentInfoDTO.setEmailDate(DateUtil.format(message.getSentDate(), DateConst.YYYY_MM_DD_HH_MM_SS));
  103. emailContentInfoDTOList.add(emailContentInfoDTO);
  104. }
  105. return emailContentInfoDTOList;
  106. }
  107. private static boolean isSupportedFileType(String fileName) {
  108. if (StrUtil.isBlank(fileName)) {
  109. return false;
  110. }
  111. return ExcelUtil.isZip(fileName) || ExcelUtil.isExcel(fileName) || ExcelUtil.isPdf(fileName) || ExcelUtil.isHTML(fileName);
  112. }
  113. /**
  114. * 根据日期过滤邮件
  115. *
  116. * @param messages 采集到的邮件
  117. * @param startDate 邮件起始日期
  118. * @param endDate 邮件截止日期
  119. * @return 符合日期的邮件
  120. */
  121. public static List<Message> filterMessage(Message[] messages, Date startDate, Date endDate) {
  122. long startTime = System.currentTimeMillis();
  123. List<Message> messageList = CollUtil.newArrayList();
  124. if (messages == null) {
  125. return messageList;
  126. }
  127. for (Message message : messages) {
  128. try {
  129. if (message.getSentDate().compareTo(startDate) >= 0 && message.getSentDate().compareTo(endDate) <= 0) {
  130. messageList.add(message);
  131. }
  132. } catch (MessagingException e) {
  133. throw new RuntimeException(e);
  134. }
  135. }
  136. logger.info("根据日期过滤邮件耗时 -> {}ms", (System.currentTimeMillis() - startTime));
  137. return messageList;
  138. }
  139. /**
  140. * 采集邮件正文
  141. *
  142. * @param part 邮件消息体
  143. * @param partContent 邮件消息内筒
  144. * @param filePath 文件路径
  145. * @param fileName 文件名
  146. * @return 采集到邮件正文(html格式包含table标签)
  147. */
  148. public static EmailContentInfoDTO collectTextPart(MimeBodyPart part, Object partContent, String filePath, String fileName) {
  149. EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  150. try {
  151. if ((part.getContentType().contains("text/html") || part.getContentType().contains("TEXT/HTML"))) {
  152. if (partContent.toString().contains("<table")) {
  153. emailContentInfoDTO.setEmailContent(partContent.toString());
  154. String savePath = filePath + fileName;
  155. File saveFile = new File(savePath);
  156. if (!saveFile.exists()) {
  157. if (!saveFile.getParentFile().exists()) {
  158. saveFile.getParentFile().mkdirs();
  159. saveFile.getParentFile().setExecutable(true);
  160. }
  161. FileUtil.writeFile(savePath, partContent.toString());
  162. }
  163. emailContentInfoDTO.setFileName(fileName);
  164. emailContentInfoDTO.setFilePath(savePath);
  165. }
  166. }
  167. } catch (MessagingException e) {
  168. logger.info("邮件正文采集失败 -> 文件名:{}, 报错堆栈:{}", fileName, ExceptionUtil.stacktraceToString(e));
  169. return emailContentInfoDTO;
  170. }
  171. return emailContentInfoDTO;
  172. }
  173. /**
  174. * 判断邮件是否符合解析条件
  175. *
  176. * @param subject 邮件主题
  177. * @param emailTypeMap 邮件类型识别规则映射表
  178. * @return 邮件类型:1-净值,2-估值表,3-定期报告 -> 兜底为净值类型
  179. */
  180. public static Integer getEmailTypeBySubject(String subject, Map<Integer, List<String>> emailTypeMap) {
  181. if (MapUtil.isEmpty(emailTypeMap)) {
  182. return EmailTypeConst.NAV_EMAIL_TYPE;
  183. }
  184. for (Map.Entry<Integer, List<String>> emailTypeEntry : emailTypeMap.entrySet()) {
  185. for (String field : emailTypeEntry.getValue()) {
  186. if (subject.contains(field)) {
  187. return emailTypeEntry.getKey();
  188. }
  189. }
  190. }
  191. return EmailTypeConst.NAV_EMAIL_TYPE;
  192. }
  193. public static Store getStoreNew(MailboxInfoDTO mailboxInfoDTO) {
  194. // 配置连接邮件服务器参数
  195. Properties props = getMailProps(mailboxInfoDTO);
  196. // 创建Session实例对象
  197. Session session = Session.getInstance(props, new JakartaUserPassAuthenticator(mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword()));
  198. Store store;
  199. try {
  200. String protocol = mailboxInfoDTO.getProtocol().equals(IMAP) ? "imaps" : "pop3";
  201. if (mailboxInfoDTO.getProtocol().contains(IMAP)) {
  202. IMAPStore imapStore = (IMAPStore) session.getStore(protocol);
  203. imapStore.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  204. // 网易邮箱需要带上身份标识,详情请看:https://www.hmail163.com/content/?404.html
  205. Map<String, String> clientParams = new HashMap<>(2);
  206. clientParams.put("name", "my-imap");
  207. clientParams.put("version", "1.0");
  208. imapStore.id(clientParams);
  209. return imapStore;
  210. } else {
  211. store = session.getStore(protocol);
  212. store.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  213. return store;
  214. }
  215. } catch (Exception e) {
  216. logger.error("邮箱信息:{},服务器参数:{}", mailboxInfoDTO, props);
  217. logger.error("连接邮箱报错堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  218. return null;
  219. }
  220. }
  221. public static Properties getMailProps(MailboxInfoDTO mailboxInfoDTO) {
  222. Properties props = new Properties();
  223. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(POP3)) {
  224. props.put("mail.pop3.host", mailboxInfoDTO.getHost());
  225. props.put("mail.pop3.user", mailboxInfoDTO.getAccount());
  226. props.put("mail.pop3.socketFactory", mailboxInfoDTO.getPort());
  227. props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  228. props.put("mail.pop3.port", mailboxInfoDTO.getPort());
  229. props.put("mail.store.protocol", mailboxInfoDTO.getProtocol());
  230. }
  231. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(IMAP)) {
  232. props.put("mail.store.protocol", "imaps");
  233. props.put("mail.imap.host", mailboxInfoDTO.getHost());
  234. props.put("mail.imap.port", mailboxInfoDTO.getPort());
  235. props.put("mail.imaps.ssl.enable", "true");
  236. props.put("mail.imaps.ssl.trust", "*");
  237. props.put("mail.imap.auth", "true");
  238. props.put("mail.imap.starttls.enable", "true");
  239. props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  240. props.put("mail.imap.socketFactory.fallback", "false");
  241. }
  242. return props;
  243. }
  244. public static void senEmail(MailboxInfoDTO mailboxInfoDTO, String emails, File file, JavaMailSender javaMailSender) throws Exception {
  245. logger.info("send email begin .........");
  246. // 根据Session 构建邮件信息
  247. MimeMessage message = javaMailSender.createMimeMessage();
  248. // 创建邮件发送者地址
  249. Address from = new InternetAddress(mailboxInfoDTO.getAccount());
  250. String[] emailArr = emails.split(";");
  251. Address[] toArr = new Address[emailArr.length];
  252. for (int idx = 0; idx < emailArr.length; idx++) {
  253. if (StringUtils.isNotEmpty(emailArr[idx])) {
  254. Address to = new InternetAddress(emailArr[idx]);
  255. toArr[idx] = to;
  256. }
  257. }
  258. message.setFrom(from);
  259. message.setRecipients(Message.RecipientType.TO, toArr);
  260. // 邮件主题
  261. message.setSubject("产品净值补发");
  262. // 邮件容器
  263. MimeMultipart mimeMultiPart = new MimeMultipart();
  264. // 设置HTML
  265. BodyPart bodyPart = new MimeBodyPart();
  266. logger.info("组装 htmlText.........");
  267. // 邮件内容
  268. String htmlText = "<p>您好,附件为产品的数据未发送到最新,麻烦尽快发送缺失的数据。若是产品清算或者有其他原因不再发送数据,还请将产品的清算日期或者不再发送数据的原因发送给我们,非常感谢~\n</p>";
  269. bodyPart.setContent(htmlText, "text/html;charset=utf-8");
  270. //设置附件
  271. BodyPart filePart = new MimeBodyPart();
  272. filePart.setFileName(file.getName());
  273. filePart.setDataHandler(
  274. new DataHandler(
  275. new ByteArrayDataSource(
  276. Files.readAllBytes(Paths.get(file.getAbsolutePath())), "application/octet-stream")));
  277. mimeMultiPart.addBodyPart(bodyPart);
  278. mimeMultiPart.addBodyPart(filePart);
  279. message.setContent(mimeMultiPart);
  280. message.setSentDate(new Date());
  281. // 保存邮件
  282. message.saveChanges();
  283. // 发送邮件
  284. javaMailSender.send(message);
  285. }
  286. }