EmailUtil.java 15 KB

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