智能仲裁后端服务

EmailOutUtil.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. package com.ruoyi.common.utils;
  2. import com.ruoyi.common.utils.uuid.UUID;
  3. import lombok.Data;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.mail.SimpleMailMessage;
  7. import org.springframework.mail.javamail.JavaMailSender;
  8. import org.springframework.mail.javamail.JavaMailSenderImpl;
  9. import org.springframework.mail.javamail.MimeMessageHelper;
  10. import org.springframework.stereotype.Component;
  11. import javax.activation.DataHandler;
  12. import javax.mail.*;
  13. import javax.mail.internet.*;
  14. import javax.mail.search.*;
  15. import javax.mail.util.ByteArrayDataSource;
  16. import javax.validation.constraints.NotNull;
  17. import java.io.*;
  18. import java.nio.file.Files;
  19. import java.nio.file.Paths;
  20. import java.security.Security;
  21. import java.util.*;
  22. import java.util.regex.Matcher;
  23. import java.util.regex.Pattern;
  24. import java.util.stream.Stream;
  25. /**
  26. * @ClassName EmailInUtil
  27. * @Description 邮件发送工具
  28. */
  29. @Component
  30. @Data
  31. @Slf4j
  32. public class EmailOutUtil {
  33. private static Pattern emailPattern = Pattern.compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
  34. // private static Pattern phonePattern = Pattern.compile("0?(13|14|15|18)[0-9]{9}");
  35. private static Pattern phonePattern = Pattern.compile("^1\\d{10}$");
  36. // @Autowired
  37. // private JavaMailSender mailSender;
  38. // 发送发邮箱地址(外网地址)
  39. // @Value("${spring.mail-out-network.from}")
  40. // private static String fromOut;
  41. @Value("${spring.mail.host}")
  42. private String hostOut;
  43. // @Value("${spring.mail.username}")
  44. // private String usernameOut;
  45. private String usernameOut="wq18792927508@163.com";
  46. // @Value("${spring.mail.password}")
  47. // private String passwordOut;
  48. private String passwordOut= "WDFHKSEMCKVRELEA";
  49. @Value("${spring.mail.port}")
  50. private Integer portOut;
  51. public JavaMailSender rebuildMailSender() {
  52. JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
  53. mailSender.setHost(hostOut);
  54. mailSender.setUsername(usernameOut);
  55. mailSender.setPassword(passwordOut);
  56. mailSender.setPort(portOut);
  57. mailSender.setProtocol("smtp");
  58. mailSender.setDefaultEncoding("UTF-8");
  59. return mailSender;
  60. }
  61. /**
  62. * 发送纯文本邮件信息
  63. *
  64. * @param to 接收方
  65. * @param subject 邮件主题
  66. * @param content 邮件内容(发送内容)
  67. */
  68. public void sendMessage(String to, String subject, String content, String from, JavaMailSender mailSender) {
  69. // 创建一个邮件对象
  70. SimpleMailMessage msg = new SimpleMailMessage();
  71. msg.setFrom(from);
  72. msg.setTo(to);
  73. // 设置邮件主题
  74. msg.setSubject(subject);
  75. // 设置邮件内容
  76. msg.setText(content);
  77. // 发送邮件
  78. mailSender.send(msg);
  79. ////System.out.println("发送成功:" + from + ":to:" + to);
  80. }
  81. /**
  82. * @param to 收件人
  83. * @param message 邮件内容
  84. * @param subject 邮件主题
  85. * @param fileList 邮件附件
  86. */
  87. public Boolean sendEmil(String to, String message, String subject, List<File> fileList, File file) {
  88. try {
  89. String messageContent = "<html><body><p style=\"font-family: Arial, sans-serif; font-size: 18px;\">"+message+"。</p></body></html>";
  90. MimeBodyPart messageBodyPart = new MimeBodyPart();
  91. messageBodyPart.setContent(messageContent, "text/html;charset=utf-8");
  92. messageBodyPart.setContentID(UUID.randomUUID().toString());
  93. Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  94. final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  95. //设置邮件会话参数
  96. Properties props = new Properties();
  97. //邮箱的发送服务器地址
  98. props.setProperty("mail.smtp.host", "smtp.163.com");
  99. props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
  100. props.setProperty("mail.smtp.socketFactory.fallback", "false");
  101. //邮箱发送服务器端口,这里设置为465端口
  102. props.setProperty("mail.smtp.port", "465");
  103. props.setProperty("mail.smtp.socketFactory.port", "465");
  104. props.put("mail.smtp.auth", "true");
  105. //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
  106. Session session = Session.getDefaultInstance(props, new Authenticator() {
  107. @Override
  108. protected PasswordAuthentication getPasswordAuthentication() {
  109. return new PasswordAuthentication(usernameOut, passwordOut);
  110. }
  111. });
  112. //通过会话,得到一个邮件,用于发送
  113. Message msg = new MimeMessage(session);
  114. //设置发件人
  115. msg.setFrom(new InternetAddress(usernameOut));
  116. //设置收件人,to为收件人,cc为抄送,bcc为密送
  117. msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
  118. msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
  119. msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
  120. //设置邮件消息
  121. msg.setSubject(subject);
  122. msg.setText(message);
  123. msg.setDescription("messageutf-8html");
  124. //设置发送的日期
  125. msg.setSentDate(new Date());
  126. // 创建邮件正文
  127. MimeMultipart multipart = new MimeMultipart();
  128. // MimeBodyPart bodyPart = new MimeBodyPart();
  129. // bodyPart.setContent("This is the body of the email", "text/html");
  130. multipart.addBodyPart(messageBodyPart);
  131. // 添加附件
  132. if (file != null) {
  133. MimeBodyPart attachmentPart = new MimeBodyPart();
  134. attachmentPart.attachFile(file);
  135. attachmentPart.setFileName(MimeUtility.encodeText(file.getName()));
  136. multipart.addBodyPart(attachmentPart);
  137. //将multipart对象放入邮件
  138. msg.setContent(multipart);
  139. } else if (fileList != null && fileList.size() > 0) {
  140. // 添加附件(多个)
  141. if (fileList != null && fileList.size() > 0) {
  142. for (File tempfile : fileList) {
  143. MimeBodyPart attachmentPart = new MimeBodyPart();
  144. attachmentPart.attachFile(tempfile);
  145. attachmentPart.setFileName(MimeUtility.encodeText(tempfile.getName()));
  146. multipart.addBodyPart(attachmentPart);
  147. }
  148. msg.setContent(multipart);
  149. }
  150. }
  151. //调用Transport的send方法去发送邮件
  152. Transport.send(msg);
  153. }catch (Exception e) {
  154. e.printStackTrace();
  155. return Boolean.FALSE;
  156. }
  157. return Boolean.TRUE;
  158. }
  159. /**
  160. * 发送带附件的邮件信息
  161. *
  162. * @param to 接收方
  163. * @param subject 邮件主题
  164. * @param content 邮件内容(发送内容)
  165. * @param fileList 文件集合 // 可发送多个附件
  166. */
  167. public void sendMessageCarryFiles(String to, String subject, String content, List<File> fileList, String from, @NotNull JavaMailSender mailSender) {
  168. MimeMessage mimeMessage = mailSender.createMimeMessage();
  169. try {
  170. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  171. helper.setFrom(from);
  172. helper.setTo(to);
  173. // 设置邮件主题
  174. helper.setSubject(subject);
  175. // 设置邮件内容
  176. helper.setText(content);
  177. // 添加附件(多个)
  178. if (fileList != null && fileList.size() > 0) {
  179. for (File file : fileList) {
  180. helper.addAttachment(file.getName(), file);
  181. }
  182. }
  183. } catch (MessagingException e) {
  184. e.printStackTrace();
  185. }
  186. // 发送邮件
  187. mailSender.send(mimeMessage);
  188. }
  189. /**
  190. * 发送带附件的邮件信息
  191. *
  192. * @param to 接收方
  193. * @param subject 邮件主题
  194. * @param content 邮件内容(发送内容)
  195. * @param file 单个文件
  196. */
  197. public void sendMessageCarryFile(String to, String subject, String content, File file, String from, JavaMailSender mailSender) {
  198. MimeMessage mimeMessage = mailSender.createMimeMessage();
  199. try {
  200. MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
  201. helper.setFrom(from);
  202. helper.setTo(to);
  203. // 设置邮件主题
  204. helper.setSubject(subject);
  205. // 设置邮件内容
  206. helper.setText(content);
  207. // 单个附件
  208. helper.addAttachment(file.getName(), file);
  209. } catch (MessagingException e) {
  210. e.printStackTrace();
  211. }
  212. // 发送邮件
  213. mailSender.send(mimeMessage);
  214. }
  215. /**
  216. * 初始化内外网邮件发送对象
  217. *
  218. * @param num
  219. */
  220. // public static JavaMailSender initJavaMailSender(Integer num) {
  221. // if (num != null && num == 1) {
  222. // //内网
  223. // return rebuildMailSender(hostIn, usernameIn, passwordIn, Integer.parseInt(portIn), "smtps");
  224. // } else {
  225. // //外网
  226. // return rebuildMailSender(hostOut, usernameOut, passwordOut, Integer.parseInt(portOut), "smtps");
  227. // }
  228. // }
  229. // public static String getInnerFrom() {
  230. // return EmailInUtil;
  231. // }
  232. //
  233. // public static String getOutterFrom() {
  234. // return fromOut;
  235. // }
  236. /**
  237. * 验证邮箱格式
  238. *
  239. * @param str
  240. * @return
  241. */
  242. public static boolean isEmail(String str) {
  243. boolean flag = false;
  244. Matcher matcher = emailPattern.matcher(str);
  245. if (matcher.matches()) {
  246. flag = true;
  247. }
  248. return flag;
  249. }
  250. public static boolean isPhoneNumber(String str) {
  251. boolean flag = false;
  252. Matcher matcher = phonePattern.matcher(str);
  253. if (matcher.matches()) {
  254. flag = true;
  255. }
  256. return flag;
  257. }
  258. public void buildReceiveConnect() throws Exception {
  259. //POP3主机名
  260. String host = "pop3.163.com";
  261. //设置传输协议
  262. String protocol = "pop3";
  263. //用户账号
  264. String username = "wq18792927508@163.com";
  265. //密码或者授权码
  266. String password = "WDFHKSEMCKVRELEA";
  267. /*
  268. * 获取Session
  269. */
  270. Properties props = new Properties();
  271. //协议
  272. props.setProperty("mail.store.protocol", protocol);
  273. //POP3主机名
  274. props.setProperty("mail.pop3.host", host);
  275. props.setProperty("mail.smtp.auth", "true");
  276. props.setProperty("mail.pop3.default-encoding", "UTF-8");
  277. Session session = Session.getDefaultInstance(props, new Authenticator() {
  278. @Override
  279. protected PasswordAuthentication getPasswordAuthentication() {
  280. return new PasswordAuthentication(usernameOut, passwordOut);
  281. }
  282. });
  283. URLName urlName = new URLName(protocol, host, 110, null, username, password);
  284. Store store = session.getStore(urlName);
  285. store.connect(username, password);
  286. Folder folder = store.getFolder("INBOX");
  287. folder.open(Folder.READ_ONLY);
  288. }
  289. /**
  290. * 接收邮件
  291. */
  292. public List<String> receiverMail() {
  293. List<String> messageIds=new ArrayList<>();
  294. // session.setDebug(true);
  295. try {
  296. //POP3主机名
  297. String host = "pop3.163.com";
  298. //设置传输协议
  299. String protocol = "pop3";
  300. //用户账号
  301. String username = "wq18792927508@163.com";
  302. //密码或者授权码
  303. String password = "WDFHKSEMCKVRELEA";
  304. /*
  305. * 获取Session
  306. */
  307. Properties props = new Properties();
  308. //协议
  309. props.setProperty("mail.store.protocol", protocol);
  310. //POP3主机名
  311. props.setProperty("mail.pop3.host", host);
  312. props.setProperty("mail.smtp.auth", "true");
  313. props.setProperty("mail.pop3.default-encoding", "UTF-8");
  314. Session session = Session.getDefaultInstance(props, new Authenticator() {
  315. @Override
  316. protected PasswordAuthentication getPasswordAuthentication() {
  317. return new PasswordAuthentication(usernameOut, passwordOut);
  318. }
  319. });
  320. URLName urlName = new URLName(protocol, host, 110, null, username, password);
  321. Store store = session.getStore(urlName);
  322. store.connect(username, password);
  323. Folder folder = store.getFolder("INBOX");
  324. folder.open(Folder.READ_ONLY);
  325. SearchTerm orTerm = new SubjectTerm("退信");
  326. // Message[] messages = folder.search(orTerm);
  327. Date endTime= new Date();
  328. long oneDayMillis=24*60*60*1000L;
  329. Date startTime=new Date(endTime.getTime()-oneDayMillis);
  330. // SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, startTime);
  331. // SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, endTime);
  332. // SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe);
  333. // SearchTerm searchTerm = new AndTerm(comparisonAndTerm, orTerm);
  334. Message[] messages = folder.search(orTerm);
  335. if (messages != null) {
  336. Arrays.stream(messages).forEach(message -> {
  337. String messageId="";
  338. try {
  339. messageId = EmailUtil.getMessageId(message,session);
  340. } catch (Exception e) {
  341. e.printStackTrace();
  342. }
  343. messageIds.add(messageId);
  344. });
  345. }
  346. folder.close(false);
  347. store.close();
  348. } catch (Exception e) {
  349. return messageIds;
  350. }
  351. return messageIds;
  352. }
  353. public void analyseMail(Session session, Object content) throws Exception {
  354. if (content instanceof Multipart) {
  355. Multipart multipart = (Multipart) content;
  356. for (int i = 0; i < multipart.getCount(); i++) {
  357. BodyPart bodyPart = multipart.getBodyPart(i);
  358. // if (bodyPart.isMimeType("message/rfc822")) { if(bodyPart.getContentType().startsWith("Message/Rfc822"));
  359. // MimeMessage mimeMessage = new MimeMessage(session, bodyPart.getInputStream());
  360. // }
  361. if(bodyPart.isMimeType("Message/Rfc822")){
  362. MimeMessage mimeMessage = new MimeMessage(session, bodyPart.getInputStream());
  363. }
  364. }
  365. }
  366. }
  367. public static String getMessageId(Part part) throws Exception {
  368. if (!part.isMimeType("multipart/*")) {
  369. return "";
  370. }
  371. Multipart multipart = (Multipart) part.getContent();
  372. for (int i = 0; i < multipart.getCount(); i++) {
  373. BodyPart bodyPart = multipart.getBodyPart(i);
  374. if (part.isMimeType("message/rfc822")) {
  375. return getMessageId((Part) part.getContent());
  376. }
  377. InputStream inputStream = bodyPart.getInputStream();
  378. try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
  379. String strLine;
  380. while ((strLine = br.readLine()) != null) {
  381. if (strLine.startsWith("Message_Id:")) {
  382. String[] split = strLine.split("Message_Id:");
  383. return split.length > 1 ? split[1].trim() : null;
  384. }
  385. }
  386. }
  387. }
  388. return "";
  389. }
  390. //检查退信邮件
  391. // Folder folder = ...; //打开收件箱
  392. // Message[] messages = folder.getMessages();
  393. // for (Message message : messages) {
  394. // if (message.getSubject().contains("Delivery Status Notification")) {
  395. // System.out.println("Delivery failed for recipient: " + message.getRecipients()[0]);
  396. // }
  397. // }
  398. }