调解系统后端服务

EmailOutUtil.java 16KB

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