EmailUtil.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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) || ExcelUtil.isRAR(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. if(savePath.contains(":")){
  174. savePath = savePath.replaceAll(":","");
  175. }
  176. FileUtils.write(new File(savePath), html);
  177. }catch (Exception e){
  178. logger.error(e.getMessage(),e);
  179. }
  180. emailContentInfoDTO.setFileName(fileName);
  181. emailContentInfoDTO.setFilePath(savePath);
  182. }else {
  183. try {
  184. if (part.getFileName() == null) {
  185. return emailContentInfoDTO;
  186. }
  187. String fileName1 = MimeUtility.decodeText(part.getFileName());
  188. if (!isSupportedFileType(fileName1)) {
  189. return emailContentInfoDTO;
  190. }
  191. emailContentInfoDTO.setFileName(fileName1);
  192. String realPath = filePath + fileName1;
  193. File saveFile = new File(realPath);
  194. if (!saveFile.exists()) {
  195. if (!saveFile.getParentFile().exists()) {
  196. saveFile.getParentFile().mkdirs();
  197. }
  198. FileUtil.saveFile(saveFile, part);
  199. } else {
  200. FileUtils.deleteQuietly(saveFile);
  201. FileUtil.saveFile(saveFile, part);
  202. }
  203. emailContentInfoDTO.setFilePath(realPath);
  204. } catch (Exception e) {
  205. return emailContentInfoDTO;
  206. }
  207. }
  208. } catch (MessagingException e) {
  209. logger.info("邮件正文采集失败 -> 文件名:{}, 报错堆栈:{}", fileName, ExceptionUtil.stacktraceToString(e));
  210. return emailContentInfoDTO;
  211. }
  212. return emailContentInfoDTO;
  213. }
  214. /**
  215. * 判断邮件是否符合解析条件
  216. *
  217. * @param subject 邮件主题
  218. * @param emailTypeMap 邮件类型识别规则映射表
  219. * @return 邮件类型:1-净值,2-估值表,3-定期报告 -> 兜底为净值类型
  220. */
  221. public static Integer getEmailTypeBySubject(String subject, Map<Integer, List<String>> emailTypeMap) {
  222. if (MapUtil.isEmpty(emailTypeMap) || StrUtil.isBlank(subject)) {
  223. return EmailTypeConst.NAV_EMAIL_TYPE;
  224. }
  225. for (Map.Entry<Integer, List<String>> emailTypeEntry : emailTypeMap.entrySet()) {
  226. for (String field : emailTypeEntry.getValue()) {
  227. if (subject.contains(field)) {
  228. return emailTypeEntry.getKey();
  229. }
  230. }
  231. }
  232. return EmailTypeConst.NAV_EMAIL_TYPE;
  233. }
  234. public static Store getStoreNew(MailboxInfoDTO mailboxInfoDTO) {
  235. // 配置连接邮件服务器参数
  236. Properties props = getMailProps(mailboxInfoDTO);
  237. // 创建Session实例对象
  238. Session session = Session.getInstance(props, new JakartaUserPassAuthenticator(mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword()));
  239. Store store;
  240. try {
  241. String protocol = mailboxInfoDTO.getProtocol().equals(IMAP) ? "imaps" : "pop3";
  242. if (mailboxInfoDTO.getProtocol().contains(IMAP)) {
  243. IMAPStore imapStore = (IMAPStore) session.getStore(protocol);
  244. imapStore.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  245. // 网易邮箱需要带上身份标识,详情请看:https://www.hmail163.com/content/?404.html
  246. Map<String, String> clientParams = new HashMap<>(2);
  247. clientParams.put("name", "my-imap");
  248. clientParams.put("version", "1.0");
  249. imapStore.id(clientParams);
  250. return imapStore;
  251. } else {
  252. store = session.getStore(protocol);
  253. store.connect(mailboxInfoDTO.getHost(), mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  254. return store;
  255. }
  256. } catch (Exception e) {
  257. logger.error("邮箱信息:{},服务器参数:{}", mailboxInfoDTO, props);
  258. logger.error("连接邮箱报错堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  259. return null;
  260. }
  261. }
  262. public static Properties getMailProps(MailboxInfoDTO mailboxInfoDTO) {
  263. Properties props = new Properties();
  264. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(POP3)) {
  265. props.put("mail.pop3.host", mailboxInfoDTO.getHost());
  266. props.put("mail.pop3.user", mailboxInfoDTO.getAccount());
  267. props.put("mail.pop3.socketFactory", mailboxInfoDTO.getPort());
  268. props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  269. props.put("mail.pop3.port", mailboxInfoDTO.getPort());
  270. props.put("mail.store.protocol", mailboxInfoDTO.getProtocol());
  271. }
  272. if (mailboxInfoDTO.getProtocol().equalsIgnoreCase(IMAP)) {
  273. props.put("mail.store.protocol", "imaps");
  274. props.put("mail.imap.host", mailboxInfoDTO.getHost());
  275. props.put("mail.imap.port", mailboxInfoDTO.getPort());
  276. props.put("mail.imaps.ssl.enable", "true");
  277. props.put("mail.imaps.ssl.trust", "*");
  278. props.put("mail.imap.auth", "true");
  279. props.put("mail.imap.starttls.enable", "true");
  280. props.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  281. props.put("mail.imap.socketFactory.fallback", "false");
  282. }
  283. return props;
  284. }
  285. public static void senEmail(MailboxInfoDTO mailboxInfoDTO, String emails, File file,String htmlText) throws Exception {
  286. logger.info("send email begin .........");
  287. // 根据Session 构建邮件信息
  288. MimeMessage message = new MimeMessage(getSession(mailboxInfoDTO));
  289. // 创建邮件发送者地址
  290. Address from = new InternetAddress(mailboxInfoDTO.getAccount());
  291. String[] emailArr = emails.split(";");
  292. Address[] toArr = new Address[emailArr.length];
  293. for (int idx = 0; idx < emailArr.length; idx++) {
  294. if (StringUtils.isNotEmpty(emailArr[idx])) {
  295. Address to = new InternetAddress(emailArr[idx]);
  296. toArr[idx] = to;
  297. }
  298. }
  299. message.setFrom(from);
  300. message.setRecipients(Message.RecipientType.TO, toArr);
  301. // 邮件主题
  302. message.setSubject("产品净值补发");
  303. // 邮件容器
  304. MimeMultipart mimeMultiPart = new MimeMultipart();
  305. // 设置HTML
  306. BodyPart bodyPart = new MimeBodyPart();
  307. logger.info("组装 htmlText.........");
  308. // 邮件内容
  309. bodyPart.setContent(htmlText, "text/html;charset=utf-8");
  310. //设置附件
  311. BodyPart filePart = new MimeBodyPart();
  312. filePart.setFileName(file.getName());
  313. filePart.setDataHandler(
  314. new DataHandler(
  315. new ByteArrayDataSource(
  316. Files.readAllBytes(Paths.get(file.getAbsolutePath())), "application/octet-stream")));
  317. mimeMultiPart.addBodyPart(bodyPart);
  318. mimeMultiPart.addBodyPart(filePart);
  319. message.setContent(mimeMultiPart);
  320. message.setSentDate(new Date());
  321. // 保存邮件
  322. message.saveChanges();
  323. // 发送邮件
  324. Transport.send(message);
  325. }
  326. public static Session getSession(MailboxInfoDTO mailboxInfoDTO){
  327. try{
  328. Properties properties = new Properties();
  329. properties.put("mail.smtp.host", mailboxInfoDTO.getHost());
  330. properties.put("mail.smtp.auth", true);
  331. properties.setProperty("mail.smtp.port", mailboxInfoDTO.getPort());
  332. properties.put("mail.smtp.ssl.enable", true);
  333. // 根据邮件的会话属性构造一个发送邮件的Session,
  334. JakartaUserPassAuthenticator authenticator = new JakartaUserPassAuthenticator(mailboxInfoDTO.getAccount(), mailboxInfoDTO.getPassword());
  335. Session session = Session.getInstance(properties, authenticator);
  336. return session;
  337. }catch(Exception e){
  338. logger.error("getSession : "+e.getMessage());
  339. }
  340. return null;
  341. }
  342. }