EmailUtil.java 17 KB

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