歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring MVC發送郵件

Spring MVC發送郵件

日期:2017/3/1 10:21:13   编辑:Linux編程

Spring發送html郵件一文件闡述了使用Spring發送html郵件的方法,根據該文,作者寫了一個綜合的發送郵件的工具類MailUtil,如下所示:

  1. /**
  2. *
  3. * @author geloin
  4. * @date 2012-5-8 上午11:02:41
  5. */
  6. package com.embest.ruisystem.util;
  7. import java.io.File;
  8. import java.util.ArrayList;
  9. import java.util.HashMap;
  10. import java.util.Iterator;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Properties;
  14. import javax.mail.Session;
  15. import javax.mail.internet.MimeMessage;
  16. import org.springframework.core.io.FileSystemResource;
  17. import org.springframework.mail.javamail.JavaMailSenderImpl;
  18. import org.springframework.mail.javamail.MimeMessageHelper;
  19. /**
  20. *
  21. * @author geloin
  22. * @date 2012-5-8 上午11:02:41
  23. */
  24. public class MailUtil {
  25. /**
  26. * 發件人郵箱服務器
  27. */
  28. private String emailHost;
  29. /**
  30. * 發件人郵箱
  31. */
  32. private String emailFrom;
  33. /**
  34. * 發件人用戶名
  35. */
  36. private String emailUserName;
  37. /**
  38. * 發件人密碼
  39. */
  40. private String emailPassword;
  41. /**
  42. * 收件人郵箱,多個郵箱以“;”分隔
  43. */
  44. private String toEmails;
  45. /**
  46. * 郵件主題
  47. */
  48. private String subject;
  49. /**
  50. * 郵件內容
  51. */
  52. private String content;
  53. /**
  54. * 郵件中的圖片,為空時無圖片。map中的key為圖片ID,value為圖片地址
  55. */
  56. private Map<String, String> pictures;
  57. /**
  58. * 郵件中的附件,為空時無附件。map中的key為附件ID,value為附件地址
  59. */
  60. private Map<String, String> attachments;
  61. /**
  62. *
  63. * @author geloin
  64. * @date 2012-5-9 上午10:49:01
  65. * @return the emailHost
  66. */
  67. public String getEmailHost() {
  68. emailHost = DataUtil.objToStr(emailHost);
  69. if (emailHost.equals("")) {
  70. emailHost = Constants.emailHost;
  71. }
  72. return emailHost;
  73. }
  74. /**
  75. *
  76. * @author geloin
  77. * @date 2012-5-9 上午10:49:01
  78. * @param emailHost
  79. * the emailHost to set
  80. */
  81. public void setEmailHost(String emailHost) {
  82. this.emailHost = emailHost;
  83. }
  84. /**
  85. *
  86. * @author geloin
  87. * @date 2012-5-9 上午10:49:01
  88. * @return the emailFrom
  89. */
  90. public String getEmailFrom() {
  91. emailFrom = DataUtil.objToStr(emailFrom);
  92. if (emailFrom.equals("")) {
  93. emailFrom = Constants.emailFrom;
  94. }
  95. return emailFrom;
  96. }
  97. /**
  98. *
  99. * @author geloin
  100. * @date 2012-5-9 上午10:49:01
  101. * @param emailFrom
  102. * the emailFrom to set
  103. */
  104. public void setEmailFrom(String emailFrom) {
  105. this.emailFrom = emailFrom;
  106. }
  107. /**
  108. *
  109. * @author geloin
  110. * @date 2012-5-9 上午10:49:01
  111. * @return the emailUserName
  112. */
  113. public String getEmailUserName() {
  114. emailUserName = DataUtil.objToStr(emailUserName);
  115. if (emailUserName.equals("")) {
  116. emailUserName = Constants.emailUsername;
  117. }
  118. return emailUserName;
  119. }
  120. /**
  121. *
  122. * @author geloin
  123. * @date 2012-5-9 上午10:49:01
  124. * @param emailUserName
  125. * the emailUserName to set
  126. */
  127. public void setEmailUserName(String emailUserName) {
  128. this.emailUserName = emailUserName;
  129. }
  130. /**
  131. *
  132. * @author geloin
  133. * @date 2012-5-9 上午10:49:01
  134. * @return the emailPassword
  135. */
  136. public String getEmailPassword() {
  137. emailPassword = DataUtil.objToStr(emailPassword);
  138. if (emailPassword.equals("")) {
  139. emailPassword = Constants.emailPassword;
  140. }
  141. return emailPassword;
  142. }
  143. /**
  144. *
  145. * @author geloin
  146. * @date 2012-5-9 上午10:49:01
  147. * @param emailPassword
  148. * the emailPassword to set
  149. */
  150. public void setEmailPassword(String emailPassword) {
  151. this.emailPassword = emailPassword;
  152. }
  153. /**
  154. *
  155. * @author geloin
  156. * @date 2012-5-9 上午10:49:01
  157. * @return the toEmails
  158. */
  159. public String getToEmails() {
  160. return DataUtil.objToStr(toEmails);
  161. }
  162. /**
  163. *
  164. * @author geloin
  165. * @date 2012-5-9 上午10:49:01
  166. * @param toEmails
  167. * the toEmails to set
  168. */
  169. public void setToEmails(String toEmails) {
  170. this.toEmails = toEmails;
  171. }
  172. /**
  173. *
  174. * @author geloin
  175. * @date 2012-5-9 上午10:49:01
  176. * @return the subject
  177. */
  178. public String getSubject() {
  179. subject = DataUtil.objToStr(subject);
  180. if (subject.equals("")) {
  181. subject = "無主題";
  182. }
  183. return DataUtil.objToStr(subject);
  184. }
  185. /**
  186. *
  187. * @author geloin
  188. * @date 2012-5-9 上午10:49:01
  189. * @param subject
  190. * the subject to set
  191. */
  192. public void setSubject(String subject) {
  193. this.subject = subject;
  194. }
  195. /**
  196. *
  197. * @author geloin
  198. * @date 2012-5-9 上午10:49:01
  199. * @return the content
  200. */
  201. public String getContent() {
  202. return DataUtil.objToStr(content);
  203. }
  204. /**
  205. *
  206. * @author geloin
  207. * @date 2012-5-9 上午10:49:01
  208. * @param content
  209. * the content to set
  210. */
  211. public void setContent(String content) {
  212. this.content = content;
  213. }
  214. /**
  215. *
  216. * @author geloin
  217. * @date 2012-5-9 上午10:49:01
  218. * @return the pictures
  219. */
  220. public Map<String, String> getPictures() {
  221. return pictures;
  222. }
  223. /**
  224. *
  225. * @author geloin
  226. * @date 2012-5-9 上午10:49:01
  227. * @param pictures
  228. * the pictures to set
  229. */
  230. public void setPictures(Map<String, String> pictures) {
  231. this.pictures = pictures;
  232. }
  233. /**
  234. *
  235. * @author geloin
  236. * @date 2012-5-9 上午10:49:01
  237. * @return the attachments
  238. */
  239. public Map<String, String> getAttachments() {
  240. return attachments;
  241. }
  242. /**
  243. *
  244. * @author geloin
  245. * @date 2012-5-9 上午10:49:01
  246. * @param attachments
  247. * the attachments to set
  248. */
  249. public void setAttachments(Map<String, String> attachments) {
  250. this.attachments = attachments;
  251. }
  252. /**
  253. * 發送郵件
  254. *
  255. * @author geloin
  256. * @date 2012-5-9 上午11:18:21
  257. * @throws Exception
  258. */
  259. public void sendEmail() throws Exception {
  260. if (this.getEmailHost().equals("") || this.getEmailFrom().equals("")
  261. || this.getEmailUserName().equals("")
  262. || this.getEmailPassword().equals("")) {
  263. throw new RuntimeException("發���人信息不完全,請確認發件人信息!");
  264. }
  265. JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
  266. // 設定mail server
  267. senderImpl.setHost(emailHost);
  268. // 建立郵件消息
  269. MimeMessage mailMessage = senderImpl.createMimeMessage();
  270. MimeMessageHelper messageHelper = null;
  271. messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8");
  272. // 設置發件人郵箱
  273. messageHelper.setFrom(emailFrom);
  274. // 設置收件人郵箱
  275. String[] toEmailArray = toEmails.split(";");
  276. List<String> toEmailList = new ArrayList<String>();
  277. if (null == toEmailArray || toEmailArray.length <= 0) {
  278. throw new RuntimeException("收件人郵箱不得為空!");
  279. } else {
  280. for (String s : toEmailArray) {
  281. s = DataUtil.objToStr(s);
  282. if (!s.equals("")) {
  283. toEmailList.add(s);
  284. }
  285. }
  286. if (null == toEmailList || toEmailList.size() <= 0) {
  287. throw new RuntimeException("收件人郵箱不得為空!");
  288. } else {
  289. toEmailArray = new String[toEmailList.size()];
  290. for (int i = 0; i < toEmailList.size(); i++) {
  291. toEmailArray[i] = toEmailList.get(i);
  292. }
  293. }
  294. }
  295. messageHelper.setTo(toEmailArray);
  296. // 郵件主題
  297. messageHelper.setSubject(subject);
  298. // true 表示啟動HTML格式的郵件
  299. messageHelper.setText(content, true);
  300. // 添加圖片
  301. if (null != pictures) {
  302. for (Iterator<Map.Entry<String, String>> it = pictures.entrySet()
  303. .iterator(); it.hasNext();) {
  304. Map.Entry<String, String> entry = it.next();
  305. String cid = entry.getKey();
  306. String filePath = entry.getValue();
  307. if (null == cid || null == filePath) {
  308. throw new RuntimeException("請確認每張圖片的ID和圖片地址是否齊全!");
  309. }
  310. File file = new File(filePath);
  311. if (!file.exists()) {
  312. throw new RuntimeException("圖片" + filePath + "不存在!");
  313. }
  314. FileSystemResource img = new FileSystemResource(file);
  315. messageHelper.addInline(cid, img);
  316. }
  317. }
  318. // 添加附件
  319. if (null != attachments) {
  320. for (Iterator<Map.Entry<String, String>> it = attachments
  321. .entrySet().iterator(); it.hasNext();) {
  322. Map.Entry<String, String> entry = it.next();
  323. String cid = entry.getKey();
  324. String filePath = entry.getValue();
  325. if (null == cid || null == filePath) {
  326. throw new RuntimeException("請確認每個附件的ID和地址是否齊全!");
  327. }
  328. File file = new File(filePath);
  329. if (!file.exists()) {
  330. throw new RuntimeException("附件" + filePath + "不存在!");
  331. }
  332. FileSystemResource fileResource = new FileSystemResource(file);
  333. messageHelper.addAttachment(cid, fileResource);
  334. }
  335. }
  336. Properties prop = new Properties();
  337. prop.put("mail.smtp.auth", "true"); // 將這個參數設為true,讓服務器進行認證,認證用戶名和密碼是否正確
  338. prop.put("mail.smtp.timeout", "25000");
  339. // 添加驗證
  340. MyAuthenticator auth = new MyAuthenticator(emailUserName, emailPassword);
  341. Session session = Session.getDefaultInstance(prop, auth);
  342. senderImpl.setSession(session);
  343. // 發送郵件
  344. senderImpl.send(mailMessage);
  345. }
  346. public static void main(String[] args) throws Exception {
  347. MailUtil mu = new MailUtil();
  348. // test1(mu);
  349. // test2(mu);
  350. // test3(mu);
  351. // test4(mu);
  352. // test5(mu);
  353. test6(mu);
  354. }
  355. public static void test1(MailUtil mu) throws Exception {
  356. String toEmails = "[email protected]";
  357. String subject = "第一封,簡單文本郵件";
  358. StringBuilder builder = new StringBuilder();
  359. builder.append("我相信天上不會掉餡餅");
  360. String content = builder.toString();
  361. mu.setToEmails(toEmails);
  362. mu.setSubject(subject);
  363. mu.setContent(content);
  364. mu.sendEmail();
  365. }
  366. public static void test2(MailUtil mu) throws Exception {
  367. String toEmails = "[email protected]";
  368. String subject = "第二封,HTML郵件";
  369. StringBuilder builder = new StringBuilder();
  370. builder.append("<html><body>老婆:<br />我是你的老公嗎?<br />是的,是很久了。<br /></body></html>");
  371. String content = builder.toString();
  372. mu.setToEmails(toEmails);
  373. mu.setSubject(subject);
  374. mu.setContent(content);
  375. mu.sendEmail();
  376. }
  377. public static void test3(MailUtil mu) throws Exception {
  378. String toEmails = "[email protected]";
  379. String subject = "第三封,圖片郵件";
  380. Map<String, String> pictures = new HashMap<String, String>();
  381. pictures.put("d1", "D:/work/download/d1.jpg");
  382. pictures.put("d2", "D:/work/download/測試圖片2.jpg");
  383. pictures.put("d3", "D:/work/download/d3.jpg");
  384. StringBuilder builder = new StringBuilder();
  385. builder.append("<html><body>看看下面的圖,你會知道花兒為什麼是這樣紅的:<br />");
  386. builder.append("<img src=\"cid:d1\" /><br />");
  387. builder.append("<img src=\"cid:d2\" /><br />");
  388. builder.append("<img src=\"cid:d3\" /><br />");
  389. builder.append("</body></html>");
  390. String content = builder.toString();
  391. mu.setToEmails(toEmails);
  392. mu.setSubject(subject);
  393. mu.setContent(content);
  394. mu.setPictures(pictures);
  395. mu.sendEmail();
  396. }
  397. public static void test4(MailUtil mu) throws Exception {
  398. String toEmails = "[email protected]";
  399. String subject = "第四封,附件郵件";
  400. Map<String, String> attachments = new HashMap<String, String>();
  401. attachments.put("d1.jar", "D:/work/download/activation.jar");
  402. attachments.put("d2.doc",
  403. "C:/Documents and Settings/Administrator/桌面/Java設計模式.doc");
  404. StringBuilder builder = new StringBuilder();
  405. builder.append("<html><body>看看附件中的資料,你會知道世界為什麼是平的。</body></html>");
  406. String content = builder.toString();
  407. mu.setToEmails(toEmails);
  408. mu.setSubject(subject);
  409. mu.setContent(content);
  410. mu.setAttachments(attachments);
  411. mu.sendEmail();
  412. }
  413. public static void test5(MailUtil mu) throws Exception {
  414. String toEmails = "[email protected]";
  415. String subject = "第五封,綜合郵件";
  416. Map<String, String> attachments = new HashMap<String, String>();
  417. attachments.put("d1.jar", "D:/work/download/activation.jar");
  418. attachments.put("d2.doc",
  419. "C:/Documents and Settings/Administrator/桌面/Java設計模式.doc");
  420. Map<String, String> pictures = new HashMap<String, String>();
  421. pictures.put("d1", "D:/work/download/d1.jpg");
  422. pictures.put("d2", "D:/work/download/測試圖片2.jpg");
  423. pictures.put("d3", "D:/work/download/d3.jpg");
  424. StringBuilder builder = new StringBuilder();
  425. builder.append("<html><body>看看附件中的資料,你會知道世界為什麼是平的。<br />");
  426. builder.append("看看下面的圖,你會知道花兒為什麼是這樣紅的:<br />");
  427. builder.append("<img src=\"cid:d1\" /><br />");
  428. builder.append("<img src=\"cid:d2\" /><br />");
  429. builder.append("<img src=\"cid:d3\" /><br />");
  430. builder.append("</body></html>");
  431. String content = builder.toString();
  432. mu.setToEmails(toEmails);
  433. mu.setSubject(subject);
  434. mu.setContent(content);
  435. mu.setPictures(pictures);
  436. mu.setAttachments(attachments);
  437. mu.sendEmail();
  438. }
  439. public static void test6(MailUtil mu) throws Exception {
  440. String toEmails = "[email protected];[email protected]";
  441. String subject = "第五封,群發郵件";
  442. Map<String, String> attachments = new HashMap<String, String>();
  443. attachments.put("d1.jar", "D:/work/download/activation.jar");
  444. attachments.put("d2.doc",
  445. "C:/Documents and Settings/Administrator/桌面/Java設計模式.doc");
  446. Map<String, String> pictures = new HashMap<String, String>();
  447. pictures.put("d1", "D:/work/download/d1.jpg");
  448. pictures.put("d2", "D:/work/download/測試圖片2.jpg");
  449. pictures.put("d3", "D:/work/download/d3.jpg");
  450. StringBuilder builder = new StringBuilder();
  451. builder.append("<html><body>看看附件中的資料,你會知道世界為什麼是平的。<br />");
  452. builder.append("看看下面的圖,你會知道花兒為什麼是這樣紅的:<br />");
  453. builder.append("<img src=\"cid:d1\" /><br />");
  454. builder.append("<img src=\"cid:d2\" /><br />");
  455. builder.append("<img src=\"cid:d3\" /><br />");
  456. builder.append("</body></html>");
  457. String content = builder.toString();
  458. mu.setToEmails(toEmails);
  459. mu.setSubject(subject);
  460. mu.setContent(content);
  461. mu.setPictures(pictures);
  462. mu.setAttachments(attachments);
  463. mu.sendEmail();
  464. }
  465. }
Copyright © Linux教程網 All Rights Reserved