Spring發送html郵件一文件闡述了使用Spring發送html郵件的方法,根據該文,作者寫了一個綜合的發送郵件的工具類MailUtil,如下所示:
- /**
- *
- * @author geloin
- * @date 2012-5-8 上午11:02:41
- */
- package com.embest.ruisystem.util;
-
- import java.io.File;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Properties;
-
- import javax.mail.Session;
- import javax.mail.internet.MimeMessage;
-
- import org.springframework.core.io.FileSystemResource;
- import org.springframework.mail.javamail.JavaMailSenderImpl;
- import org.springframework.mail.javamail.MimeMessageHelper;
-
- /**
- *
- * @author geloin
- * @date 2012-5-8 上午11:02:41
- */
- public class MailUtil {
-
- /**
- * 發件人郵箱服務器
- */
- private String emailHost;
- /**
- * 發件人郵箱
- */
- private String emailFrom;
-
- /**
- * 發件人用戶名
- */
- private String emailUserName;
-
- /**
- * 發件人密碼
- */
- private String emailPassword;
-
- /**
- * 收件人郵箱,多個郵箱以“;”分隔
- */
- private String toEmails;
- /**
- * 郵件主題
- */
- private String subject;
- /**
- * 郵件內容
- */
- private String content;
- /**
- * 郵件中的圖片,為空時無圖片。map中的key為圖片ID,value為圖片地址
- */
- private Map<String, String> pictures;
- /**
- * 郵件中的附件,為空時無附件。map中的key為附件ID,value為附件地址
- */
- private Map<String, String> attachments;
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the emailHost
- */
- public String getEmailHost() {
- emailHost = DataUtil.objToStr(emailHost);
- if (emailHost.equals("")) {
- emailHost = Constants.emailHost;
- }
- return emailHost;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param emailHost
- * the emailHost to set
- */
- public void setEmailHost(String emailHost) {
- this.emailHost = emailHost;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the emailFrom
- */
- public String getEmailFrom() {
- emailFrom = DataUtil.objToStr(emailFrom);
- if (emailFrom.equals("")) {
- emailFrom = Constants.emailFrom;
- }
- return emailFrom;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param emailFrom
- * the emailFrom to set
- */
- public void setEmailFrom(String emailFrom) {
- this.emailFrom = emailFrom;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the emailUserName
- */
- public String getEmailUserName() {
- emailUserName = DataUtil.objToStr(emailUserName);
- if (emailUserName.equals("")) {
- emailUserName = Constants.emailUsername;
- }
- return emailUserName;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param emailUserName
- * the emailUserName to set
- */
- public void setEmailUserName(String emailUserName) {
- this.emailUserName = emailUserName;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the emailPassword
- */
- public String getEmailPassword() {
- emailPassword = DataUtil.objToStr(emailPassword);
- if (emailPassword.equals("")) {
- emailPassword = Constants.emailPassword;
- }
- return emailPassword;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param emailPassword
- * the emailPassword to set
- */
- public void setEmailPassword(String emailPassword) {
- this.emailPassword = emailPassword;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the toEmails
- */
- public String getToEmails() {
- return DataUtil.objToStr(toEmails);
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param toEmails
- * the toEmails to set
- */
- public void setToEmails(String toEmails) {
- this.toEmails = toEmails;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the subject
- */
- public String getSubject() {
- subject = DataUtil.objToStr(subject);
- if (subject.equals("")) {
- subject = "無主題";
- }
- return DataUtil.objToStr(subject);
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param subject
- * the subject to set
- */
- public void setSubject(String subject) {
- this.subject = subject;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the content
- */
- public String getContent() {
- return DataUtil.objToStr(content);
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param content
- * the content to set
- */
- public void setContent(String content) {
- this.content = content;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the pictures
- */
- public Map<String, String> getPictures() {
- return pictures;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param pictures
- * the pictures to set
- */
- public void setPictures(Map<String, String> pictures) {
- this.pictures = pictures;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @return the attachments
- */
- public Map<String, String> getAttachments() {
- return attachments;
- }
-
- /**
- *
- * @author geloin
- * @date 2012-5-9 上午10:49:01
- * @param attachments
- * the attachments to set
- */
- public void setAttachments(Map<String, String> attachments) {
- this.attachments = attachments;
- }
-
- /**
- * 發送郵件
- *
- * @author geloin
- * @date 2012-5-9 上午11:18:21
- * @throws Exception
- */
- public void sendEmail() throws Exception {
-
- if (this.getEmailHost().equals("") || this.getEmailFrom().equals("")
- || this.getEmailUserName().equals("")
- || this.getEmailPassword().equals("")) {
- throw new RuntimeException("發���人信息不完全,請確認發件人信息!");
- }
-
- JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
-
- // 設定mail server
- senderImpl.setHost(emailHost);
-
- // 建立郵件消息
- MimeMessage mailMessage = senderImpl.createMimeMessage();
-
- MimeMessageHelper messageHelper = null;
- messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8");
- // 設置發件人郵箱
- messageHelper.setFrom(emailFrom);
-
- // 設置收件人郵箱
- String[] toEmailArray = toEmails.split(";");
- List<String> toEmailList = new ArrayList<String>();
- if (null == toEmailArray || toEmailArray.length <= 0) {
- throw new RuntimeException("收件人郵箱不得為空!");
- } else {
- for (String s : toEmailArray) {
- s = DataUtil.objToStr(s);
- if (!s.equals("")) {
- toEmailList.add(s);
- }
- }
- if (null == toEmailList || toEmailList.size() <= 0) {
- throw new RuntimeException("收件人郵箱不得為空!");
- } else {
- toEmailArray = new String[toEmailList.size()];
- for (int i = 0; i < toEmailList.size(); i++) {
- toEmailArray[i] = toEmailList.get(i);
- }
- }
- }
- messageHelper.setTo(toEmailArray);
-
- // 郵件主題
- messageHelper.setSubject(subject);
-
- // true 表示啟動HTML格式的郵件
- messageHelper.setText(content, true);
-
- // 添加圖片
- if (null != pictures) {
- for (Iterator<Map.Entry<String, String>> it = pictures.entrySet()
- .iterator(); it.hasNext();) {
- Map.Entry<String, String> entry = it.next();
- String cid = entry.getKey();
- String filePath = entry.getValue();
- if (null == cid || null == filePath) {
- throw new RuntimeException("請確認每張圖片的ID和圖片地址是否齊全!");
- }
-
- File file = new File(filePath);
- if (!file.exists()) {
- throw new RuntimeException("圖片" + filePath + "不存在!");
- }
-
- FileSystemResource img = new FileSystemResource(file);
- messageHelper.addInline(cid, img);
- }
- }
-
- // 添加附件
- if (null != attachments) {
- for (Iterator<Map.Entry<String, String>> it = attachments
- .entrySet().iterator(); it.hasNext();) {
- Map.Entry<String, String> entry = it.next();
- String cid = entry.getKey();
- String filePath = entry.getValue();
- if (null == cid || null == filePath) {
- throw new RuntimeException("請確認每個附件的ID和地址是否齊全!");
- }
-
- File file = new File(filePath);
- if (!file.exists()) {
- throw new RuntimeException("附件" + filePath + "不存在!");
- }
-
- FileSystemResource fileResource = new FileSystemResource(file);
- messageHelper.addAttachment(cid, fileResource);
- }
- }
-
- Properties prop = new Properties();
- prop.put("mail.smtp.auth", "true"); // 將這個參數設為true,讓服務器進行認證,認證用戶名和密碼是否正確
- prop.put("mail.smtp.timeout", "25000");
- // 添加驗證
- MyAuthenticator auth = new MyAuthenticator(emailUserName, emailPassword);
-
- Session session = Session.getDefaultInstance(prop, auth);
- senderImpl.setSession(session);
-
- // 發送郵件
- senderImpl.send(mailMessage);
- }
-
- public static void main(String[] args) throws Exception {
- MailUtil mu = new MailUtil();
- // test1(mu);
- // test2(mu);
- // test3(mu);
- // test4(mu);
- // test5(mu);
- test6(mu);
- }
-
- public static void test1(MailUtil mu) throws Exception {
- String toEmails = "[email protected]";
- String subject = "第一封,簡單文本郵件";
- StringBuilder builder = new StringBuilder();
- builder.append("我相信天上不會掉餡餅");
- String content = builder.toString();
-
- mu.setToEmails(toEmails);
- mu.setSubject(subject);
- mu.setContent(content);
-
- mu.sendEmail();
- }
-
- public static void test2(MailUtil mu) throws Exception {
- String toEmails = "[email protected]";
- String subject = "第二封,HTML郵件";
- StringBuilder builder = new StringBuilder();
- builder.append("<html><body>老婆:<br />我是你的老公嗎?<br />是的,是很久了。<br /></body></html>");
- String content = builder.toString();
-
- mu.setToEmails(toEmails);
- mu.setSubject(subject);
- mu.setContent(content);
-
- mu.sendEmail();
- }
-
- public static void test3(MailUtil mu) throws Exception {
- String toEmails = "[email protected]";
- String subject = "第三封,圖片郵件";
-
- Map<String, String> pictures = new HashMap<String, String>();
- pictures.put("d1", "D:/work/download/d1.jpg");
- pictures.put("d2", "D:/work/download/測試圖片2.jpg");
- pictures.put("d3", "D:/work/download/d3.jpg");
-
- StringBuilder builder = new StringBuilder();
- builder.append("<html><body>看看下面的圖,你會知道花兒為什麼是這樣紅的:<br />");
- builder.append("<img src=\"cid:d1\" /><br />");
- builder.append("<img src=\"cid:d2\" /><br />");
- builder.append("<img src=\"cid:d3\" /><br />");
- builder.append("</body></html>");
- String content = builder.toString();
-
- mu.setToEmails(toEmails);
- mu.setSubject(subject);
- mu.setContent(content);
- mu.setPictures(pictures);
-
- mu.sendEmail();
-
- }
-
- public static void test4(MailUtil mu) throws Exception {
- String toEmails = "[email protected]";
- String subject = "第四封,附件郵件";
- Map<String, String> attachments = new HashMap<String, String>();
- attachments.put("d1.jar", "D:/work/download/activation.jar");
- attachments.put("d2.doc",
- "C:/Documents and Settings/Administrator/桌面/Java設計模式.doc");
- StringBuilder builder = new StringBuilder();
- builder.append("<html><body>看看附件中的資料,你會知道世界為什麼是平的。</body></html>");
- String content = builder.toString();
-
- mu.setToEmails(toEmails);
- mu.setSubject(subject);
- mu.setContent(content);
- mu.setAttachments(attachments);
-
- mu.sendEmail();
- }
-
- public static void test5(MailUtil mu) throws Exception {
- String toEmails = "[email protected]";
- String subject = "第五封,綜合郵件";
-
- Map<String, String> attachments = new HashMap<String, String>();
- attachments.put("d1.jar", "D:/work/download/activation.jar");
- attachments.put("d2.doc",
- "C:/Documents and Settings/Administrator/桌面/Java設計模式.doc");
-
- Map<String, String> pictures = new HashMap<String, String>();
- pictures.put("d1", "D:/work/download/d1.jpg");
- pictures.put("d2", "D:/work/download/測試圖片2.jpg");
- pictures.put("d3", "D:/work/download/d3.jpg");
-
- StringBuilder builder = new StringBuilder();
- builder.append("<html><body>看看附件中的資料,你會知道世界為什麼是平的。<br />");
- builder.append("看看下面的圖,你會知道花兒為什麼是這樣紅的:<br />");
- builder.append("<img src=\"cid:d1\" /><br />");
- builder.append("<img src=\"cid:d2\" /><br />");
- builder.append("<img src=\"cid:d3\" /><br />");
- builder.append("</body></html>");
- String content = builder.toString();
-
- mu.setToEmails(toEmails);
- mu.setSubject(subject);
- mu.setContent(content);
- mu.setPictures(pictures);
- mu.setAttachments(attachments);
-
- mu.sendEmail();
- }
-
- public static void test6(MailUtil mu) throws Exception {
- String toEmails = "[email protected];[email protected]";
- String subject = "第五封,群發郵件";
-
- Map<String, String> attachments = new HashMap<String, String>();
- attachments.put("d1.jar", "D:/work/download/activation.jar");
- attachments.put("d2.doc",
- "C:/Documents and Settings/Administrator/桌面/Java設計模式.doc");
-
- Map<String, String> pictures = new HashMap<String, String>();
- pictures.put("d1", "D:/work/download/d1.jpg");
- pictures.put("d2", "D:/work/download/測試圖片2.jpg");
- pictures.put("d3", "D:/work/download/d3.jpg");
-
- StringBuilder builder = new StringBuilder();
- builder.append("<html><body>看看附件中的資料,你會知道世界為什麼是平的。<br />");
- builder.append("看看下面的圖,你會知道花兒為什麼是這樣紅的:<br />");
- builder.append("<img src=\"cid:d1\" /><br />");
- builder.append("<img src=\"cid:d2\" /><br />");
- builder.append("<img src=\"cid:d3\" /><br />");
- builder.append("</body></html>");
- String content = builder.toString();
-
- mu.setToEmails(toEmails);
- mu.setSubject(subject);
- mu.setContent(content);
- mu.setPictures(pictures);
- mu.setAttachments(attachments);
-
- mu.sendEmail();
- }
-
- }