SampleMail.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package com.szwl.model.utils;
  2. import javax.mail.*;
  3. import javax.mail.internet.InternetAddress;
  4. import javax.mail.internet.MimeMessage;
  5. import java.io.UnsupportedEncodingException;
  6. import java.util.Date;
  7. import java.util.Properties;
  8. import java.util.UUID;
  9. public class SampleMail {
  10. protected static String genMessageID(String mailFrom) {
  11. // message-id 必须符合 first-part@last-part
  12. String[] mailInfo = mailFrom.split("@");
  13. String domain = mailFrom;
  14. int index = mailInfo.length - 1;
  15. if (index >= 0) {
  16. domain = mailInfo[index];
  17. }
  18. UUID uuid = UUID.randomUUID();
  19. StringBuffer messageId = new StringBuffer();
  20. messageId.append('<').append(uuid.toString()).append('@').append(domain).append('>');
  21. return messageId.toString();
  22. }
  23. public void sendAuthCode(String toEmail, String content) {
  24. // 配置发送邮件的环境属性
  25. final Properties props = new Properties();
  26. // 表示SMTP发送邮件,需要进行身份验证
  27. props.put("mail.smtp.auth", "true");
  28. props.put("mail.smtp.host", "smtpdm.aliyun.com"); //华东1:smtpdm.aliyun.com,悉尼:smtpdm-ap-southeast-2.aliyun.com
  29. //设置端口:
  30. props.put("mail.smtp.port", "80");//或"25"
  31. props.put("mail.smtp.from", "robot@suncee.cn"); //mailfrom 参数
  32. props.put("mail.user", "robot@suncee.cn");// 发件人的账号(在控制台创建的发信地址)
  33. props.put("mail.password", "DirectMail123");// 发信地址的smtp密码(在控制台选择发信地址进行设置)
  34. System.setProperty("mail.mime.splitlongparameters", "false");//用于解决附件名过长导致的显示异常
  35. // 构建授权信息,用于进行SMTP进行身份验证
  36. Authenticator authenticator = new Authenticator() {
  37. @Override
  38. protected PasswordAuthentication getPasswordAuthentication() {
  39. // 用户名、密码
  40. String userName = props.getProperty("mail.user");
  41. String password = props.getProperty("mail.password");
  42. return new PasswordAuthentication(userName, password);
  43. }
  44. };
  45. //使用环境属性和授权信息,创建邮件会话
  46. Session mailSession = Session.getInstance(props, authenticator);
  47. //mailSession.setDebug(true);//开启debug模式
  48. final String messageIDValue = genMessageID(props.getProperty("mail.user"));
  49. //创建邮件消息
  50. MimeMessage message = new MimeMessage(mailSession) {
  51. @Override
  52. protected void updateMessageID() throws MessagingException {
  53. //设置自定义Message-ID值
  54. setHeader("Message-ID", messageIDValue);//创建Message-ID
  55. }
  56. };
  57. try {
  58. // 设置发件人邮件地址和名称。填写控制台配置的发信地址。和上面的mail.user保持一致。名称用户可以自定义填写。
  59. InternetAddress from = new InternetAddress("robot@suncee.cn", "Cotton Candy Robot");//from 参数,可实现代发,注意:代发容易被收信方拒信或进入垃圾箱。
  60. message.setFrom(from);
  61. //可选。设置回信地址
  62. Address[] a = new Address[1];
  63. a[0] = new InternetAddress(toEmail);
  64. message.setReplyTo(a);
  65. // 设置收件人邮件地址
  66. InternetAddress to = new InternetAddress(toEmail);
  67. message.setRecipient(MimeMessage.RecipientType.TO, to);
  68. message.setSentDate(new Date()); //设置时间
  69. //设置邮件标题
  70. message.setSubject("Verification Code");
  71. message.setContent(content, "text/html;charset=UTF-8");//html超文本;// "text/plain;charset=UTF-8" //纯文本。
  72. // 发送邮件
  73. Transport.send(message);
  74. } catch (MessagingException e) {
  75. String err = e.getMessage();
  76. // 在这里处理message内容, 格式是固定的
  77. System.out.println(err);
  78. } catch (UnsupportedEncodingException e) {
  79. e.printStackTrace();
  80. }
  81. }
  82. public void sendAuthCodePortalmcc(String toEmail, String content) {
  83. // 配置发送邮件的环境属性
  84. final Properties props = new Properties();
  85. // 表示SMTP发送邮件,需要进行身份验证
  86. props.put("mail.smtp.auth", "true");
  87. props.put("mail.smtp.host", "smtpdm.aliyun.com"); //华东1:smtpdm.aliyun.com,悉尼:smtpdm-ap-southeast-2.aliyun.com,(美国(原悉尼)):smtpdm-us-east-1.aliyuncs.com
  88. //设置端口:
  89. props.put("mail.smtp.port", "80"); //或"25"
  90. props.put("mail.smtp.from", "support@portalmcc.com.cn"); //mailfrom 参数
  91. props.put("mail.user", "support@portalmcc.com.cn"); // 发件人的账号(在控制台创建的发信地址)
  92. props.put("mail.password", "DirectMail321"); // 发信地址的smtp密码(在控制台选择发信地址进行设置)
  93. System.setProperty("mail.mime.splitlongparameters", "false"); //用于解决附件名过长导致的显示异常
  94. // 构建授权信息,用于进行SMTP进行身份验证
  95. Authenticator authenticator = new Authenticator() {
  96. @Override
  97. protected PasswordAuthentication getPasswordAuthentication() {
  98. // 用户名、密码
  99. String userName = props.getProperty("mail.user");
  100. String password = props.getProperty("mail.password");
  101. return new PasswordAuthentication(userName, password);
  102. }
  103. };
  104. //使用环境属性和授权信息,创建邮件会话
  105. Session mailSession = Session.getInstance(props, authenticator);
  106. //mailSession.setDebug(true); //开启debug模式
  107. final String messageIDValue = genMessageID(props.getProperty("mail.user"));
  108. //创建邮件消息
  109. MimeMessage message = new MimeMessage(mailSession) {
  110. @Override
  111. protected void updateMessageID() throws MessagingException {
  112. //设置自定义Message-ID值
  113. setHeader("Message-ID", messageIDValue); //创建Message-ID
  114. }
  115. };
  116. try {
  117. // 设置发件人邮件地址和名称。填写控制台配置的发信地址。和上面的mail.user保持一致。名称用户可以自定义填写。
  118. InternetAddress from = new InternetAddress("support@portalmcc.com.cn", "Cotton Candy Robot"); //from 参数,可实现代发,注意:代发容易被收信方拒信或进入垃圾箱。
  119. message.setFrom(from);
  120. //可选。设置回信地址
  121. Address[] a = new Address[1];
  122. a[0] = new InternetAddress(toEmail);
  123. message.setReplyTo(a);
  124. // 设置收件人邮件地址
  125. InternetAddress to = new InternetAddress(toEmail);
  126. message.setRecipient(MimeMessage.RecipientType.TO, to);
  127. message.setSentDate(new Date()); //设置时间
  128. //设置邮件标题
  129. message.setSubject("Verification Code");
  130. message.setContent(content, "text/html;charset=UTF-8"); //html超文本;// "text/plain;charset=UTF-8" //纯文本。
  131. // 发送邮件
  132. Transport.send(message);
  133. } catch (MessagingException e) {
  134. String err = e.getMessage();
  135. // 在这里处理message内容, 格式是固定的
  136. System.out.println(err);
  137. } catch (UnsupportedEncodingException e) {
  138. e.printStackTrace();
  139. }
  140. }
  141. // public static void main(String[] args) {
  142. // // 配置发送邮件的环境属性
  143. // final Properties props = new Properties();
  144. //
  145. // // 表示SMTP发送邮件,需要进行身份验证
  146. // props.put("mail.smtp.auth", "true");
  147. // props.put("mail.smtp.host", "smtpdm.aliyun.com"); //华东1:smtpdm.aliyun.com,悉尼:smtpdm-ap-southeast-2.aliyun.com,新加坡:smtpdm-ap-southeast-1.aliyuncs.com
  148. // //设置端口:
  149. // props.put("mail.smtp.port", "80");//或"25", 如果使用ssl,则去掉使用80或25端口的配置,进行如下配置:
  150. // //加密方式:
  151. // //props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  152. // //props.put("mail.smtp.socketFactory.port", "465");
  153. // //props.put("mail.smtp.port", "465");
  154. //
  155. // props.put("mail.smtp.from", "robot@suncee.cn"); //mailfrom 参数
  156. // props.put("mail.user", "robot@suncee.cn");// 发件人的账号(在控制台创建的发信地址)
  157. // props.put("mail.password", "DirectMail123");// 发信地址的smtp密码(在控制台选择发信地址进行设置)
  158. // //props.setProperty("mail.smtp.ssl.enable", "true"); //请配合465端口使用
  159. // System.setProperty("mail.mime.splitlongparameters", "false");//用于解决附件名过长导致的显示异常
  160. // //props.put("mail.smtp.connectiontimeout", 1000);
  161. //
  162. // // 构建授权信息,用于进行SMTP进行身份验证
  163. // Authenticator authenticator = new Authenticator() {
  164. // @Override
  165. // protected PasswordAuthentication getPasswordAuthentication() {
  166. // // 用户名、密码
  167. // String userName = props.getProperty("mail.user");
  168. // String password = props.getProperty("mail.password");
  169. // return new PasswordAuthentication(userName, password);
  170. // }
  171. // };
  172. //
  173. // //使用环境属性和授权信息,创建邮件会话
  174. // Session mailSession = Session.getInstance(props, authenticator);
  175. // //mailSession.setDebug(true);//开启debug模式
  176. //
  177. //
  178. // final String messageIDValue = genMessageID(props.getProperty("mail.user"));
  179. // //创建邮件消息
  180. // MimeMessage message = new MimeMessage(mailSession) {
  181. // @Override
  182. // protected void updateMessageID() throws MessagingException {
  183. // //设置自定义Message-ID值
  184. // setHeader("Message-ID", messageIDValue);//创建Message-ID
  185. // }
  186. // };
  187. //
  188. // try {
  189. // // 设置发件人邮件地址和名称。填写控制台配置的发信地址。和上面的mail.user保持一致。名称用户可以自定义填写。
  190. // InternetAddress from = new InternetAddress("robot@suncee.cn", "发件人名称");//from 参数,可实现代发,注意:代发容易被收信方拒信或进入垃圾箱。
  191. // message.setFrom(from);
  192. //
  193. // //可选。设置回信地址
  194. // Address[] a = new Address[1];
  195. // a[0] = new InternetAddress("ritchie@linuxmail.org");
  196. // message.setReplyTo(a);
  197. //
  198. // // 设置收件人邮件地址
  199. // InternetAddress to = new InternetAddress("ritchie@linuxmail.org");
  200. // message.setRecipient(MimeMessage.RecipientType.TO, to);
  201. // //如果同时发给多人,才将上面两行替换为如下(因为部分收信系统的一些限制,尽量每次投递给一个人;同时我们限制单次允许发送的人数,具体参考规格清单):
  202. // //InternetAddress[] adds = new InternetAddress[2];
  203. // //adds[0] = new InternetAddress("收信地址");
  204. // //adds[1] = new InternetAddress("收信地址");
  205. // //message.setRecipients(Message.RecipientType.TO, adds);
  206. //
  207. // message.setSentDate(new Date()); //设置时间
  208. //// String ccUser = "抄送地址";
  209. //// // 设置多个抄送地址
  210. //// if (null != ccUser && !ccUser.isEmpty()) {
  211. //// @SuppressWarnings("static-access")
  212. //// InternetAddress[] internetAddressCC = new InternetAddress().parse(ccUser);
  213. //// message.setRecipients(Message.RecipientType.CC, internetAddressCC);
  214. //// }
  215. //// String bccUser = "密送地址";
  216. //// // 设置多个密送地址
  217. //// if (null != bccUser && !bccUser.isEmpty()) {
  218. //// @SuppressWarnings("static-access")
  219. //// InternetAddress[] internetAddressBCC = new InternetAddress().parse(bccUser);
  220. //// message.setRecipients(Message.RecipientType.BCC, internetAddressBCC);
  221. //// }
  222. // //设置邮件标题
  223. // message.setSubject("测试主题");
  224. // message.setContent("测试<br> 内容", "text/html;charset=UTF-8");//html超文本;// "text/plain;charset=UTF-8" //纯文本。
  225. //
  226. //// //若需要开启邮件跟踪服务,请使用以下代码设置跟踪链接头。前置条件和约束见文档"如何开启数据跟踪功能?"
  227. //// String tagName = "Test";
  228. //// HashMap<String, String> trace = new HashMap<>();
  229. //// //这里为字符串"1"
  230. //// trace.put("OpenTrace", "1"); //打开邮件跟踪
  231. //// trace.put("LinkTrace", "1"); //点击邮件里的URL跟踪
  232. //// trace.put("TagName", tagName); //控制台创建的标签tagname
  233. //// String jsonTrace = new GsonBuilder().setPrettyPrinting().create().toJson(trace);
  234. //// //System.out.println(jsonTrace);
  235. //// String base64Trace = new String(Base64.getEncoder().encode(jsonTrace.getBytes()));
  236. //// //设置跟踪链接头
  237. //// message.addHeader("X-AliDM-Trace", base64Trace);
  238. //// //邮件eml原文中的示例值:X-AliDM-Trace: eyJUYWdOYW1lIjoiVGVzdCIsIk9wZW5UcmFjZSI6IjEiLCJMaW5rVHJhY2UiOiIxIn0=
  239. //
  240. ////发送附件和内容:
  241. //// BodyPart messageBodyPart = new MimeBodyPart();
  242. //// //messageBodyPart.setText("消息<br>Text");//设置邮件的内容,文本
  243. //// messageBodyPart.setContent("测试<br> 内容", "text/html;charset=UTF-8");// 纯文本:"text/plain;charset=UTF-8" //设置邮件的内容
  244. //// //创建多重消息
  245. //// Multipart multipart = new MimeMultipart();
  246. //// //设置文本消息部分
  247. //// multipart.addBodyPart(messageBodyPart);
  248. //
  249. //// //附件部分
  250. //// //发送附件,总的邮件大小不超过15M,创建消息部分。
  251. // //发送本地附件
  252. //// String[] fileList = new String[2];
  253. //// fileList[0] = "C:\\Users\\test1.txt";
  254. //// fileList[1] = "C:\\Users\\test2.txt";
  255. //// for (int index = 0; index < fileList.length; index++) {
  256. //// MimeBodyPart mimeBodyPart = new MimeBodyPart();
  257. //// // //设置要发送附件的文件路径
  258. //// FileDataSource filesdata = new FileDataSource(fileList[index]);
  259. //// mimeBodyPart.setDataHandler(new DataHandler(filesdata));
  260. //// //处理附件名称中文(附带文件路径)乱码问题
  261. //// mimeBodyPart.setFileName(MimeUtility.encodeWord("自定义附件名.xlsx"));
  262. //// mimeBodyPart.addHeader("Content-Transfer-Encoding", "base64");
  263. //// multipart.addBodyPart(mimeBodyPart);
  264. //// }
  265. //
  266. //
  267. // //发送URL附件
  268. //// String[] fileList = new String[2];
  269. //// fileList[0] = "https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx1.png";
  270. //// fileList[1] = "https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx2.png";
  271. //// for (int index = 0; index < fileList.length; index++) {
  272. //// String encode = URLEncoder.encode(fileList[index], "UTF-8");
  273. //// MimeBodyPart mimeBodyPart = new MimeBodyPart();
  274. //// mimeBodyPart.setDataHandler(new DataHandler(new URLDataSource(new URL(encode.replace("%3A",":").replace("%2F","/")))));
  275. //// mimeBodyPart.setFileName(MimeUtility.encodeText("自定义附件名.xlsx"));
  276. //// multipart.addBodyPart(mimeBodyPart);
  277. //// }
  278. //
  279. //
  280. //// //发送含有附件的完整消息
  281. //// message.setContent(multipart);
  282. //// // 发送附件代码,结束
  283. //
  284. // // 发送邮件
  285. // Transport.send(message);
  286. //
  287. // } catch (MessagingException e) {
  288. // String err = e.getMessage();
  289. // // 在这里处理message内容, 格式是固定的
  290. // System.out.println(err);
  291. // } catch (UnsupportedEncodingException e) {
  292. // // TODO Auto-generated catch block
  293. // e.printStackTrace();
  294. // } //catch (MalformedURLException e) {
  295. // // e.printStackTrace();
  296. // //}
  297. // }
  298. }