EmailUtil.java 21 KB

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