EmailUtil.java 21 KB

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