sping mvc mail

来源:互联网 发布:动感照片制作软件 编辑:程序博客网 时间:2024/04/20 07:12

   Spring发送html邮件一文件阐述了使用Spring发送html邮件的方法,根据该文,作者写了一个综合的发送邮件的工具类MailUtil,如下所示:

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

        上文的sendEmail方法即为发送邮件的主要方法,test1-test6分别是各种邮件的示例。

        上文中的MyAuthenticator辅助类为发件人信息验证类,该类代码如下所示:

[java] view plaincopy
  1. /** 
  2.  * 
  3.  * @author geloin 
  4.  * @date 2012-5-8 下午2:48:25 
  5.  */  
  6. package com.embest.ruisystem.util;  
  7.   
  8. import javax.mail.Authenticator;  
  9. import javax.mail.PasswordAuthentication;  
  10.   
  11. /** 
  12.  *  
  13.  * @author geloin 
  14.  * @date 2012-5-8 下午2:48:25 
  15.  */  
  16. public class MyAuthenticator extends Authenticator {  
  17.     private String username;  
  18.     private String password;  
  19.   
  20.     /** 
  21.      *  
  22.      * @author geloin 
  23.      * @date 2012-5-8 下午2:48:53 
  24.      * @param username 
  25.      * @param password 
  26.      */  
  27.     public MyAuthenticator(String username, String password) {  
  28.         super();  
  29.         this.username = username;  
  30.         this.password = password;  
  31.     }  
  32.   
  33.     protected PasswordAuthentication getPasswordAuthentication() {  
  34.         return new PasswordAuthentication(username, password);  
  35.     }  
  36. }  

        MailUtil中的Constants是作者自定义的一个工具类,该类的主要作用是从配置文件中获取发件人信息,包括发件人服务器、发件人邮箱、发件人账户和密码等。

        DataUtil.objToStr(String str)方法的主要作用是判断str是否为null或空字符串,若是,则返回空字符串,否则返回str.trim()。

原创粉丝点击