EmailUtil.java 15 KB

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