EmailUtil.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package com.smppw.modaq.application.util;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.collection.ListUtil;
  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.smppw.modaq.common.conts.EmailTypeConst;
  9. import com.smppw.modaq.common.conts.PatternConsts;
  10. import com.smppw.modaq.common.enums.ReportType;
  11. import com.smppw.modaq.domain.dto.MailboxInfoDTO;
  12. import com.sun.mail.imap.IMAPStore;
  13. import jakarta.mail.MessagingException;
  14. import jakarta.mail.Part;
  15. import jakarta.mail.Session;
  16. import jakarta.mail.Store;
  17. import jakarta.mail.internet.MimeUtility;
  18. import org.slf4j.Logger;
  19. import org.slf4j.LoggerFactory;
  20. import java.io.UnsupportedEncodingException;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.Properties;
  25. import java.util.regex.Matcher;
  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. // 解码文件名(处理 RFC 2231 和 RFC 2047)
  36. public static String decodeFileName(Part part) throws UnsupportedEncodingException, MessagingException {
  37. String filename = part.getFileName();
  38. logger.info("0======================= > {}", filename);
  39. // 优先尝试 RFC 2231 的 filename*(如 "filename*=utf-8''%E4%B8%AD%E6%96%87.txt")
  40. String[] values = part.getHeader("Content-Disposition");
  41. if (values != null) {
  42. for (String value : values) {
  43. if (value.startsWith("filename*")) {
  44. filename = value.split("'")[2]; // 提取编码后的字符串
  45. filename = MimeUtility.decodeText(filename);
  46. logger.info("1=======================+++++++++ > {}", filename);
  47. return filename;
  48. }
  49. }
  50. }
  51. // 处理 RFC 2047 的多段编码(如 "=?utf-8?B?5Lit?= =?utf-8?B?5paH?=.txt")
  52. if (filename != null && filename.contains("=?")) {
  53. logger.info("2=======================----------- > {}", MimeUtility.decodeText(filename));
  54. return MimeUtility.decodeText(filename);
  55. }
  56. return filename;
  57. }
  58. // /**
  59. // * 采集邮件(多消息体)信息
  60. // *
  61. // * @param message 邮件
  62. // * @param emailAddress 邮箱地址
  63. // * @param path 存储路径
  64. // * @return 从邮箱采集到的信息
  65. // * @throws Exception 异常信息
  66. // */
  67. // public static List<EmailContentInfoDTO> collectMimeMultipart(Message message, String emailAddress, String path) throws Exception {
  68. // List<EmailContentInfoDTO> emailContentInfoDTOList = CollUtil.newArrayList();
  69. // String emailTitle = message.getSubject();
  70. // String emailDate = DateUtils.format(message.getSentDate(), DateConst.YYYYMMDDHHMMSS24);
  71. // String emailDateStr = DateUtils.format(message.getSentDate(), DateConst.YYYYMMDD);
  72. // String filePath = path + File.separator + emailAddress + File.separator + emailDateStr + File.separator;
  73. //
  74. // MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
  75. // int length = mimeMultipart.getCount();
  76. // // 遍历邮件消息体 (我这里不要html正文)
  77. // for (int i = 0; i < length; i++) {
  78. // EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  79. // MimeBodyPart part = (MimeBodyPart) mimeMultipart.getBodyPart(i);
  80. // Object partContent = part.getContent();
  81. // String contentClass = part.getContent().getClass().getSimpleName();
  82. // // 1.邮件正文
  83. // switch (contentClass) {
  84. // case "String" -> {
  85. // // 文件名 = 邮件主题 + 邮件日期
  86. // String fileName = emailTitle + "_" + emailDate + ".html";
  87. // String content = partContent.toString();
  88. // emailContentInfoDTO = collectTextPart(part, content, filePath, fileName);
  89. // }
  90. // case "BASE64DecoderStream" -> {
  91. // if (StrUtil.isNotBlank(part.getFileName())) {
  92. // String fileName = MimeUtility.decodeText(part.getFileName());
  93. // if (isSupportedFileType(fileName)) {
  94. // continue;
  95. // }
  96. // emailContentInfoDTO.setFileName(fileName);
  97. //
  98. // String realPath = filePath + emailDate + fileName;
  99. //
  100. // File saveFile = cn.hutool.core.io.FileUtil.file(realPath);
  101. // if (!saveFile.exists()) {
  102. // if (!saveFile.getParentFile().exists()) {
  103. // saveFile.getParentFile().mkdirs();
  104. // }
  105. // FileUtil.saveFile(saveFile, part);
  106. // } else {
  107. // cn.hutool.core.io.FileUtil.del(saveFile);
  108. // FileUtil.saveFile(saveFile, part);
  109. // }
  110. // emailContentInfoDTO.setFilePath(realPath);
  111. // }
  112. // }
  113. // case "MimeMultipart" -> {
  114. // MimeMultipart contentPart = (MimeMultipart) partContent;
  115. // int length2 = contentPart.getCount();
  116. // for (int i2 = 0; i2 < length2; i2++) {
  117. // part = (MimeBodyPart) contentPart.getBodyPart(i2);
  118. // partContent = part.getContent();
  119. // contentClass = partContent.getClass().getSimpleName();
  120. // if ("String".equals(contentClass)) {
  121. // // 文件名 = 邮件主题 + 邮件日期
  122. // String fileName = emailTitle + "_" + emailDate + ".html";
  123. // String content = partContent.toString();
  124. // emailContentInfoDTO = collectTextPart(part, content, filePath, fileName);
  125. // }
  126. // }
  127. // }
  128. // }
  129. // String filepath = emailContentInfoDTO.getFilePath();
  130. // if (emailContentInfoDTO.getEmailContent() == null && filepath == null) {
  131. // continue;
  132. // }
  133. // emailContentInfoDTO.setEmailAddress(emailAddress);
  134. // emailContentInfoDTO.setEmailTitle(emailTitle);
  135. // emailContentInfoDTO.setEmailDate(DateUtils.format(message.getSentDate(), DateConst.YYYY_MM_DD_HH_MM_SS));
  136. // emailContentInfoDTOList.add(emailContentInfoDTO);
  137. // }
  138. //
  139. // return emailContentInfoDTOList;
  140. // }
  141. // private static List<EmailContentInfoDTO> zipFile(String filepath) {
  142. // return null;
  143. // }
  144. // private static boolean isSupportedFileType(String fileName) {
  145. // if (StrUtil.isBlank(fileName)) {
  146. // return true;
  147. // }
  148. // return !ExcelUtil.isZip(fileName) && !ExcelUtil.isExcel(fileName) && !ExcelUtil.isPdf(fileName) && !ExcelUtil.isHTML(fileName) && !ExcelUtil.isRAR(fileName);
  149. // }
  150. // /**
  151. // * 根据日期过滤邮件
  152. // *
  153. // * @param messages 采集到的邮件
  154. // * @param startDate 邮件起始日期
  155. // * @param endDate 邮件截止日期
  156. // * @return 符合日期的邮件
  157. // */
  158. // public static List<Message> filterMessage(Message[] messages, Date startDate, Date endDate) {
  159. // long startTime = System.currentTimeMillis();
  160. // List<Message> messageList = CollUtil.newArrayList();
  161. // if (messages == null) {
  162. // return messageList;
  163. // }
  164. // for (Message message : messages) {
  165. // try {
  166. // if (message.getSentDate().compareTo(startDate) >= 0 && message.getSentDate().compareTo(endDate) <= 0) {
  167. // messageList.add(message);
  168. // }
  169. // } catch (MessagingException e) {
  170. // throw new RuntimeException(e);
  171. // }
  172. // }
  173. // logger.info("根据日期过滤邮件耗时 -> {}ms", (System.currentTimeMillis() - startTime));
  174. // return messageList;
  175. // }
  176. // /**
  177. // * 采集邮件正文
  178. // *
  179. // * @param part 邮件消息体
  180. // * @param partContent 邮件消息内筒
  181. // * @param filePath 文件路径
  182. // * @param fileName 文件名
  183. // * @return 采集到邮件正文(html格式包含table标签)
  184. // */
  185. // public static EmailContentInfoDTO collectTextPart(MimeBodyPart part, String partContent, String filePath, String fileName) {
  186. // EmailContentInfoDTO emailContentInfoDTO = new EmailContentInfoDTO();
  187. // try {
  188. // if ((part.getContentType().contains("text/html") || part.getContentType().contains("TEXT/HTML"))) {
  189. // emailContentInfoDTO.setEmailContent(partContent);
  190. // String savePath = filePath + fileName;
  191. // File saveFile = new File(savePath);
  192. // if (!saveFile.exists()) {
  193. // if (!saveFile.getParentFile().exists()) {
  194. // saveFile.getParentFile().mkdirs();
  195. // saveFile.getParentFile().setExecutable(true);
  196. // }
  197. // }
  198. // //获取邮件编码
  199. // String contentType = part.getContentType();
  200. // String html = partContent.toString();
  201. // try {
  202. // if (contentType.contains("charset=")) {
  203. // contentType = contentType.substring(contentType.indexOf("charset=") + 8).replaceAll("\"", "");
  204. // html = html.replace("charset=" + contentType.toLowerCase(), "charset=UTF-8");
  205. // html = html.replace("charset=" + contentType.toUpperCase(), "charset=UTF-8");
  206. // }
  207. // if (savePath.contains(":")) {
  208. // savePath = savePath.replaceAll(":", "");
  209. // }
  210. // cn.hutool.core.io.FileUtil.writeUtf8String(html, new File(savePath));
  211. // } catch (Exception e) {
  212. // logger.error(e.getMessage(), e);
  213. // }
  214. // emailContentInfoDTO.setFileName(fileName);
  215. // emailContentInfoDTO.setFilePath(savePath);
  216. // } else {
  217. // try {
  218. // if (part.getFileName() == null) {
  219. // return emailContentInfoDTO;
  220. // }
  221. // String fileName1 = MimeUtility.decodeText(part.getFileName());
  222. // if (isSupportedFileType(fileName1)) {
  223. // return emailContentInfoDTO;
  224. // }
  225. // emailContentInfoDTO.setFileName(fileName1);
  226. // String realPath = filePath + fileName1;
  227. // File saveFile = new File(realPath);
  228. // if (!saveFile.exists()) {
  229. // if (!saveFile.getParentFile().exists()) {
  230. // saveFile.getParentFile().mkdirs();
  231. // }
  232. // FileUtil.saveFile(saveFile, part);
  233. // } else {
  234. // cn.hutool.core.io.FileUtil.del(saveFile);
  235. // FileUtil.saveFile(saveFile, part);
  236. // }
  237. // emailContentInfoDTO.setFilePath(realPath);
  238. // } catch (Exception e) {
  239. // return emailContentInfoDTO;
  240. // }
  241. // }
  242. // } catch (MessagingException e) {
  243. // logger.info("邮件正文采集失败 -> 文件名:{}, 报错堆栈:{}", fileName, ExceptionUtil.stacktraceToString(e));
  244. // return emailContentInfoDTO;
  245. // }
  246. // return emailContentInfoDTO;
  247. // }
  248. public static Map<Integer, List<String>> getEmailType() {
  249. Map<Integer, List<String>> emailTypeMap = MapUtil.newHashMap(3, true);
  250. // 1.确认函
  251. emailTypeMap.put(EmailTypeConst.REPORT_LETTER_EMAIL_TYPE,
  252. ListUtil.toList(ReportType.LETTER.getPatterns()));
  253. // 2.周报
  254. emailTypeMap.put(EmailTypeConst.REPORT_WEEKLY_TYPE,
  255. ListUtil.toList(ReportType.WEEKLY.getPatterns()));
  256. // 3.其他
  257. emailTypeMap.put(EmailTypeConst.REPORT_OTHER_TYPE,
  258. ListUtil.toList(ReportType.OTHER.getPatterns()));
  259. // 4.定期报告的类型判断
  260. List<String> types = ListUtil.list(true);
  261. CollUtil.addAll(types, ReportType.QUARTERLY.getPatterns());
  262. CollUtil.addAll(types, ReportType.ANNUALLY.getPatterns());
  263. CollUtil.addAll(types, ReportType.MONTHLY.getPatterns());
  264. emailTypeMap.put(EmailTypeConst.REPORT_EMAIL_TYPE, types);
  265. return emailTypeMap;
  266. }
  267. /**
  268. * 判断邮件是否符合解析条件
  269. *
  270. * @param subject 邮件主题
  271. * @return 邮件类型:1-净值,2-估值表,3-定期报告 -> 兜底为净值类型
  272. */
  273. public static Integer getEmailTypeBySubject(String subject) {
  274. Map<Integer, List<String>> emailTypeMap = getEmailType();
  275. if (MapUtil.isEmpty(emailTypeMap) || StrUtil.isBlank(subject)) {
  276. return EmailTypeConst.NAV_EMAIL_TYPE;
  277. }
  278. for (Map.Entry<Integer, List<String>> emailTypeEntry : emailTypeMap.entrySet()) {
  279. for (String field : emailTypeEntry.getValue()) {
  280. if (subject.contains(field)) {
  281. return emailTypeEntry.getKey();
  282. }
  283. }
  284. }
  285. // 特殊月报识别规则(没有月报或月度等关键字的月报)
  286. Matcher monthMatcher = PatternConsts.MONTHLY_PATTERN.matcher(subject);
  287. Matcher dayMatcher = PatternConsts.DAY_PATTERN.matcher(subject);
  288. if (monthMatcher.find() && !dayMatcher.find()) {
  289. return EmailTypeConst.REPORT_EMAIL_TYPE;
  290. }
  291. return EmailTypeConst.NAV_EMAIL_TYPE;
  292. }
  293. public static Store getStoreNew(MailboxInfoDTO mailboxInfoDTO) {
  294. // 配置连接邮件服务器参数
  295. Properties props = getMailProps(mailboxInfoDTO);
  296. // 创建Session实例对象
  297. Session session = Session.getInstance(props, new JakartaUserPassAuthenticator(mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword()));
  298. Store store;
  299. try {
  300. String protocol = mailboxInfoDTO.getProtocol().equals(IMAP) ? "imaps" : "pop3";
  301. if (mailboxInfoDTO.getProtocol().contains(IMAP)) {
  302. IMAPStore imapStore = (IMAPStore) session.getStore(protocol);
  303. imapStore.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  304. // 网易邮箱需要带上身份标识,详情请看:https://www.hmail163.com/content/?404.html
  305. Map<String, String> clientParams = new HashMap<>(2);
  306. clientParams.put("name", "my-imap");
  307. clientParams.put("version", "1.0");
  308. imapStore.id(clientParams);
  309. return imapStore;
  310. } else {
  311. store = session.getStore(protocol);
  312. store.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  313. return store;
  314. }
  315. } catch (Exception e) {
  316. logger.error("邮箱信息:{},服务器参数:{}", mailboxInfoDTO, props);
  317. logger.error("连接邮箱报错堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  318. return null;
  319. }
  320. }
  321. public static Properties getMailProps(MailboxInfoDTO mailboxInfoDTO) {
  322. Properties props = new Properties();
  323. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(POP3)) {
  324. props.put("mail.pop3.host", mailboxInfoDTO.getHost());
  325. props.put("mail.pop3.user", mailboxInfoDTO.getAccount());
  326. props.put("mail.pop3.socketFactory", mailboxInfoDTO.getPort());
  327. props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  328. props.put("mail.pop3.port", mailboxInfoDTO.getPort());
  329. props.put("mail.store.protocol", mailboxInfoDTO.getProtocol());
  330. }
  331. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(IMAP)) {
  332. props.put("mail.store.protocol", "imaps");
  333. props.put("mail.imap.host", mailboxInfoDTO.getHost());
  334. props.put("mail.imap.port", mailboxInfoDTO.getPort());
  335. props.put("mail.imaps.ssl.enable", "true");
  336. props.put("mail.imaps.ssl.trust", "*");
  337. props.put("mail.imap.auth", "true");
  338. props.put("mail.imap.starttls.enable", "true");
  339. props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  340. props.put("mail.imap.socketFactory.fallback", "false");
  341. // 关闭读取附件时分批获取 BASE64 输入流的配置
  342. props.put("mail.imap.partialfetch", false);
  343. props.put("mail.imaps.partialfetch", false);
  344. }
  345. return props;
  346. }
  347. // public static void senEmail(MailboxInfoDTO mailboxInfoDTO, String emails, File file, String htmlText, String host, String emailTitle) throws Exception {
  348. // logger.info("send email begin .........");
  349. // // 根据Session 构建邮件信息
  350. // MimeMessage message = new MimeMessage(getSession(mailboxInfoDTO));
  351. // // 创建邮件发送者地址
  352. // Address from = new InternetAddress(mailboxInfoDTO.getAccount() + host);
  353. // String[] emailArr = emails.split(";");
  354. // Address[] toArr = new Address[emailArr.length];
  355. // for (int idx = 0; idx < emailArr.length; idx++) {
  356. // if (StrUtil.isNotBlank(emailArr[idx])) {
  357. // Address to = new InternetAddress(emailArr[idx]);
  358. // toArr[idx] = to;
  359. // }
  360. // }
  361. // message.setFrom(from);
  362. // message.setRecipients(Message.RecipientType.TO, toArr);
  363. // // 邮件主题
  364. // message.setSubject(emailTitle);
  365. // // 邮件容器
  366. // MimeMultipart mimeMultiPart = new MimeMultipart();
  367. // // 设置HTML
  368. // BodyPart bodyPart = new MimeBodyPart();
  369. // logger.info("组装 htmlText.........");
  370. // // 邮件内容
  371. // bodyPart.setContent(htmlText, "text/html;charset=utf-8");
  372. // //设置附件
  373. // BodyPart filePart = new MimeBodyPart();
  374. // filePart.setFileName(file.getName());
  375. // filePart.setDataHandler(
  376. // new DataHandler(
  377. // new ByteArrayDataSource(
  378. // Files.readAllBytes(Paths.get(file.getAbsolutePath())), "application/octet-stream")));
  379. // mimeMultiPart.addBodyPart(bodyPart);
  380. // mimeMultiPart.addBodyPart(filePart);
  381. // message.setContent(mimeMultiPart);
  382. // message.setSentDate(new Date());
  383. // // 保存邮件
  384. // message.saveChanges();
  385. // // 发送邮件
  386. // Transport.send(message);
  387. // }
  388. // public static Session getSession(MailboxInfoDTO mailboxInfoDTO) {
  389. // try {
  390. // Properties properties = new Properties();
  391. // properties.put("mail.smtp.host", mailboxInfoDTO.getHost());
  392. // properties.put("mail.smtp.auth", true);
  393. // properties.put("mail.smtp.port", mailboxInfoDTO.getPort());
  394. // properties.put("mail.smtp.ssl.enable", true);
  395. // final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  396. // properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
  397. // properties.setProperty("mail.smtp.socketFactory.fallback", "false");
  398. // properties.setProperty("mail.smtp.socketFactory.port", mailboxInfoDTO.getPort());
  399. // // 根据邮件的会话属性构造一个发送邮件的Session,
  400. // JakartaUserPassAuthenticator authenticator = new JakartaUserPassAuthenticator(mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  401. // return Session.getInstance(properties, authenticator);
  402. // } catch (Exception e) {
  403. // logger.error("getSession : {}", e.getMessage());
  404. // }
  405. // return null;
  406. // }
  407. public static void main(String[] args) {
  408. String text = "私募基金2024年04月度报告";
  409. System.out.println(getEmailTypeBySubject(text));
  410. //
  411. // text = "私募基金202404月度报告";
  412. // System.out.println(matchReportDate(text));
  413. // System.out.println(matchReportType(3, text));
  414. //
  415. // text = "私募基金2024_04月度报告";
  416. // System.out.println(matchReportDate(text));
  417. // System.out.println(matchReportType(3, text));
  418. //
  419. // text = "私募基金2024_4月度报告";
  420. // System.out.println(matchReportDate(text));
  421. // System.out.println(matchReportType(3, text));
  422. //
  423. // text = "私募基金2024-04月度报告";
  424. // System.out.println(matchReportDate(text));
  425. // System.out.println(matchReportType(3, text));
  426. //
  427. // text = "私募基金2024_04月";
  428. // System.out.println(matchReportDate(text));
  429. // System.out.println(matchReportType(3, text));
  430. text = "私募基金2024年04月12号";
  431. System.out.println(getEmailTypeBySubject(text));
  432. text = "私募基金20240412";
  433. System.out.println(getEmailTypeBySubject(text));
  434. text = "私募基金2024041201";
  435. System.out.println(getEmailTypeBySubject(text));
  436. text = "私募基金_202404";
  437. System.out.println(getEmailTypeBySubject(text));
  438. }
  439. }