EmailUtil.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. emailContentInfoDTO.setEmailContent(partContent.toString());
  153. String savePath = filePath + fileName;
  154. File saveFile = new File(savePath);
  155. if (!saveFile.exists()) {
  156. if (!saveFile.getParentFile().exists()) {
  157. saveFile.getParentFile().mkdirs();
  158. saveFile.getParentFile().setExecutable(true);
  159. }
  160. FileUtil.writeFile(savePath, partContent.toString());
  161. }
  162. emailContentInfoDTO.setFileName(fileName);
  163. emailContentInfoDTO.setFilePath(savePath);
  164. }
  165. } catch (MessagingException e) {
  166. logger.info("邮件正文采集失败 -> 文件名:{}, 报错堆栈:{}", fileName, ExceptionUtil.stacktraceToString(e));
  167. return emailContentInfoDTO;
  168. }
  169. return emailContentInfoDTO;
  170. }
  171. /**
  172. * 判断邮件是否符合解析条件
  173. *
  174. * @param subject 邮件主题
  175. * @param emailTypeMap 邮件类型识别规则映射表
  176. * @return 邮件类型:1-净值,2-估值表,3-定期报告 -> 兜底为净值类型
  177. */
  178. public static Integer getEmailTypeBySubject(String subject, Map<Integer, List<String>> emailTypeMap) {
  179. if (MapUtil.isEmpty(emailTypeMap) || StrUtil.isBlank(subject)) {
  180. return EmailTypeConst.NAV_EMAIL_TYPE;
  181. }
  182. for (Map.Entry<Integer, List<String>> emailTypeEntry : emailTypeMap.entrySet()) {
  183. for (String field : emailTypeEntry.getValue()) {
  184. if (subject.contains(field)) {
  185. return emailTypeEntry.getKey();
  186. }
  187. }
  188. }
  189. return EmailTypeConst.NAV_EMAIL_TYPE;
  190. }
  191. public static Store getStoreNew(MailboxInfoDTO mailboxInfoDTO) {
  192. // 配置连接邮件服务器参数
  193. Properties props = getMailProps(mailboxInfoDTO);
  194. // 创建Session实例对象
  195. Session session = Session.getInstance(props, new JakartaUserPassAuthenticator(mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword()));
  196. Store store;
  197. try {
  198. String protocol = mailboxInfoDTO.getProtocol().equals(IMAP) ? "imaps" : "pop3";
  199. if (mailboxInfoDTO.getProtocol().contains(IMAP)) {
  200. IMAPStore imapStore = (IMAPStore) session.getStore(protocol);
  201. imapStore.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  202. // 网易邮箱需要带上身份标识,详情请看:https://www.hmail163.com/content/?404.html
  203. Map<String, String> clientParams = new HashMap<>(2);
  204. clientParams.put("name", "my-imap");
  205. clientParams.put("version", "1.0");
  206. imapStore.id(clientParams);
  207. return imapStore;
  208. } else {
  209. store = session.getStore(protocol);
  210. store.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  211. return store;
  212. }
  213. } catch (Exception e) {
  214. logger.error("邮箱信息:{},服务器参数:{}", mailboxInfoDTO, props);
  215. logger.error("连接邮箱报错堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  216. return null;
  217. }
  218. }
  219. public static Properties getMailProps(MailboxInfoDTO mailboxInfoDTO) {
  220. Properties props = new Properties();
  221. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(POP3)) {
  222. props.put("mail.pop3.host", mailboxInfoDTO.getHost());
  223. props.put("mail.pop3.user", mailboxInfoDTO.getAccount());
  224. props.put("mail.pop3.socketFactory", mailboxInfoDTO.getPort());
  225. props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  226. props.put("mail.pop3.port", mailboxInfoDTO.getPort());
  227. props.put("mail.store.protocol", mailboxInfoDTO.getProtocol());
  228. }
  229. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(IMAP)) {
  230. props.put("mail.store.protocol", "imaps");
  231. props.put("mail.imap.host", mailboxInfoDTO.getHost());
  232. props.put("mail.imap.port", mailboxInfoDTO.getPort());
  233. props.put("mail.imaps.ssl.enable", "true");
  234. props.put("mail.imaps.ssl.trust", "*");
  235. props.put("mail.imap.auth", "true");
  236. props.put("mail.imap.starttls.enable", "true");
  237. props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  238. props.put("mail.imap.socketFactory.fallback", "false");
  239. }
  240. return props;
  241. }
  242. public static void senEmail(MailboxInfoDTO mailboxInfoDTO, String emails, File file, JavaMailSender javaMailSender,String htmlText) throws Exception {
  243. logger.info("send email begin .........");
  244. // 根据Session 构建邮件信息
  245. MimeMessage message = javaMailSender.createMimeMessage();
  246. // 创建邮件发送者地址
  247. Address from = new InternetAddress(mailboxInfoDTO.getAccount());
  248. String[] emailArr = emails.split(";");
  249. Address[] toArr = new Address[emailArr.length];
  250. for (int idx = 0; idx < emailArr.length; idx++) {
  251. if (StringUtils.isNotEmpty(emailArr[idx])) {
  252. Address to = new InternetAddress(emailArr[idx]);
  253. toArr[idx] = to;
  254. }
  255. }
  256. message.setFrom(from);
  257. message.setRecipients(Message.RecipientType.TO, toArr);
  258. // 邮件主题
  259. message.setSubject("产品净值补发");
  260. // 邮件容器
  261. MimeMultipart mimeMultiPart = new MimeMultipart();
  262. // 设置HTML
  263. BodyPart bodyPart = new MimeBodyPart();
  264. logger.info("组装 htmlText.........");
  265. // 邮件内容
  266. bodyPart.setContent(htmlText, "text/html;charset=utf-8");
  267. //设置附件
  268. BodyPart filePart = new MimeBodyPart();
  269. filePart.setFileName(file.getName());
  270. filePart.setDataHandler(
  271. new DataHandler(
  272. new ByteArrayDataSource(
  273. Files.readAllBytes(Paths.get(file.getAbsolutePath())), "application/octet-stream")));
  274. mimeMultiPart.addBodyPart(bodyPart);
  275. mimeMultiPart.addBodyPart(filePart);
  276. message.setContent(mimeMultiPart);
  277. message.setSentDate(new Date());
  278. // 保存邮件
  279. message.saveChanges();
  280. // 发送邮件
  281. javaMailSender.send(message);
  282. }
  283. }