打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Spring发送邮件简单实例

1、spring配置文件(src/applicationContext.xml ):

Xml代码
  1. <bean id="mailSender"  
  2.     class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  3.     <property name="host" value="222.173.82.207"></property>  
  4.     <property name="javaMailProperties">  
  5.         <props>  
  6.             <prop key="mail.smtp.auth">true</prop>  
  7.             <prop key="mail.smtp.timeout">25000</prop>  
  8.         </props>  
  9.     </property>  
  10.     <property name="username" value="tiandeqing@ecode.net.cn" />  
  11.     <property name="password" value="密码" />  
  12. </bean>  
  13. <bean id="freeMarker"  
  14.     class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
  15.     <property name="templateLoaderPath" value="classpath:mail" /><!--指定模板文件目录-->  
  16.     <property name="freemarkerSettings"><!-- 设置FreeMarker环境属性-->  
  17.         <props>  
  18.             <prop key="template_update_delay">1800</prop><!--刷新模板的周期,单位为秒-->  
  19.             <prop key="default_encoding">UTF-8</prop><!--模板的编码格式 -->  
  20.             <prop key="locale">zh_CN</prop><!-- 本地化设置-->  
  21.         </props>  
  22.     </property>  
  23. </bean>  
 

2、Java代码:

给指定的单个用户发送普通文本邮件:SpringMail.java

 

Java代码
  1. package aaa;   
  2.   
  3. import java.io.StringWriter;   
  4. import java.util.HashMap;   
  5. import java.util.Map;   
  6.   
  7. import org.springframework.context.ApplicationContext;   
  8. import org.springframework.context.support.FileSystemXmlApplicationContext;   
  9. import org.springframework.mail.SimpleMailMessage;   
  10. import org.springframework.mail.javamail.JavaMailSender;   
  11.   
  12. import freemarker.template.Configuration;   
  13. import freemarker.template.Template;   
  14.   
  15. public class SpringMail {   
  16.     private Configuration cfg = new Configuration();     
  17.        
  18.  public static void main(String[] args) throws Exception {     
  19.              ApplicationContext ctx = new FileSystemXmlApplicationContext(     
  20.                      "src/applicationContext.xml");     
  21.              JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");     
  22.              SpringMail springMail = new SpringMail();     
  23.              springMail.sendMail(sender);     
  24.           
  25.          }     
  26.           
  27.          private void sendMail(JavaMailSender sender) throws Exception {     
  28.              SimpleMailMessage mail = new SimpleMailMessage();     
  29.              mail.setTo("tiandeqing@ecode.net.cn"); //接收人     
  30.              mail.setFrom("tiandeqing@ecode.net.cn"); //发送人     
  31.              mail.setSubject("test by amigo");     
  32.              //嵌入ftl模版     
  33.              cfg.setClassForTemplateLoading(getClass(), "/mail");     
  34.              Map root = new HashMap();     
  35.              root.put("username""sucre"); //模板变量     
  36.              Template t = cfg.getTemplate("notify-mail.ftl");     
  37.              StringWriter writer = new StringWriter();     
  38.              t.process(root, writer);     
  39.              //把模版内容写入邮件中     
  40.              mail.setText(writer.toString());     
  41.              sender.send(mail);     
  42.              System.out.println("邮件发送成功!");     
  43.          }     
  44.            
  45. }  

 

给指定的多个用户发送含有附件的html邮件,SpringMail_Batch_Attach_HTML.java

Java代码
  1. package aaa;   
  2.   
  3. import java.io.File;   
  4. import java.io.StringWriter;   
  5. import java.io.UnsupportedEncodingException;   
  6. import java.util.ArrayList;   
  7. import java.util.HashMap;   
  8. import java.util.List;   
  9. import java.util.Map;   
  10.   
  11. import javax.mail.Message;   
  12. import javax.mail.MessagingException;   
  13. import javax.mail.internet.InternetAddress;   
  14. import javax.mail.internet.MimeMessage;   
  15. import javax.mail.internet.MimeUtility;   
  16.   
  17. import org.springframework.context.ApplicationContext;   
  18. import org.springframework.context.support.FileSystemXmlApplicationContext;   
  19. import org.springframework.mail.SimpleMailMessage;   
  20. import org.springframework.mail.javamail.JavaMailSender;   
  21. import org.springframework.mail.javamail.MimeMessageHelper;   
  22. import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;   
  23. import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;   
  24.   
  25. import freemarker.template.Configuration;   
  26. import freemarker.template.Template;   
  27.   
  28. public class SpringMail_Batch_Attach_HTML {   
  29.     private Configuration cfg = new Configuration();   
  30.   
  31.     private static JavaMailSender sender = null;   
  32.   
  33.     private static FreeMarkerConfigurer freeMarker = null;   
  34.   
  35.     public static void main(String[] args) throws Exception {   
  36.         // init   
  37.         ApplicationContext ctx = new FileSystemXmlApplicationContext(   
  38.                 "src/applicationContext.xml");   
  39.         JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");   
  40.         SpringMail_Batch_Attach_HTML.sender = sender;   
  41.         SpringMail_Batch_Attach_HTML.freeMarker = (FreeMarkerConfigurer) ctx   
  42.                 .getBean("freeMarker");   
  43.   
  44.         SpringMail_Batch_Attach_HTML springMail = new SpringMail_Batch_Attach_HTML();   
  45.         //发送简单邮件   
  46.         springMail.sendMail(sender);   
  47.         //给某个人发送邮件,基于模板   
  48.         springMail.sendMessage("洒江河风景阿嫂法拉""wytdq@126.com");   
  49.   
  50.         //给某些人发送邮件,带附件   
  51.         List toList = new ArrayList();   
  52.         toList.add("xxx@sina.COM");   
  53.         toList.add("xxx@163.COM");   
  54.         toList.add("TIANDEQING@ECODE.NET.CN");   
  55.         springMail.sendBatchEmail("邮件批量发送测试", toList);   
  56.     }   
  57.   
  58.     // 发送一封文本邮件给一个收件人   
  59.     private void sendMail(JavaMailSender sender) throws Exception {   
  60.         SimpleMailMessage mail = new SimpleMailMessage();   
  61.         mail.setTo("tiandeqing@ecode.net.cn"); // 接收人   
  62.         mail.setFrom("tiandeqing@ecode.net.cn"); // 发送人   
  63.         mail.setSubject("test by amigo");   
  64.         // 嵌入ftl模版   
  65.         cfg.setClassForTemplateLoading(getClass(), "/mail");   
  66.         Map root = new HashMap();   
  67.         root.put("username""sucre"); // 模板变量   
  68.         Template t = cfg.getTemplate("notify-mail.ftl");   
  69.         StringWriter writer = new StringWriter();   
  70.         t.process(root, writer);   
  71.         // 把模版内容写入邮件中   
  72.         mail.setText(writer.toString());   
  73.         sender.send(mail);   
  74.         System.out.println("邮件发送成功!");   
  75.     }   
  76.   
  77.     /**  
  78.      * 发送带模板的单个html格式邮件  
  79.      *   
  80.      * @throws Exception  
  81.      */  
  82.     public void sendMessage(String content, String address) throws Exception {   
  83.         MimeMessage msg = sender.createMimeMessage();   
  84.         // 设置utf-8或GBK编码,否则邮件会有乱码,true表示为multipart邮件   
  85.         MimeMessageHelper helper = new MimeMessageHelper(msg, true"utf-8");   
  86.         helper.setTo(address); // 邮件接收地址   
  87.         helper.setFrom("tiandeqing@ecode.net.cn"); // 邮件发送地址,这里必须和xml里的邮件地址相同一致   
  88.         helper.setSubject("测试ccc"); // 主题   
  89.         String htmlText = getMailText(content); // 使用模板生成html邮件内容   
  90.         helper.setText(htmlText, true); // 邮件内容,注意加参数true,表示启用html格式   
  91.         sender.send(msg); // 发送邮件   
  92.         System.out.println("sendMessage(String content,String address) OK");   
  93.     }   
  94.   
  95.     /**  
  96.      * 批量发送多媒体邮件  
  97.      * */  
  98.     public void sendBatchEmail(String content, List address)   
  99.             throws MessagingException, UnsupportedEncodingException {   
  100.         MimeMessage msg = sender.createMimeMessage();   
  101.         MimeMessageHelper helper = new MimeMessageHelper(msg, true"utf-8");   
  102.            
  103.         StringBuffer html = new StringBuffer();   
  104.         html.append("<html>");   
  105.         html.append("<head>");   
  106.         html.append("<meta http-equiv='Content-Type' content='text/html; charset=gbk'>");   
  107.         html.append("</head>");   
  108.         html.append("<body bgcolor='#ccccff'>");   
  109.         html.append("<center>");   
  110.         html.append("<h1>你好,Jarry</h1>").append(content);   
  111.         html.append("<img src='cid:myimg'>");//显示图片   
  112.         html.append("<p>logo:");   
  113.         html.append("<img src='cid:vedio'>");   
  114.         html.append("</center>");   
  115.         html.append("</body>");   
  116.         html.append("</html>");   
  117.            
  118.         String toList = getMailList(address);   
  119.         InternetAddress[] iaToList = new InternetAddress().parse(toList);   
  120.         msg.setRecipients(Message.RecipientType.TO, iaToList);   
  121.         helper.setFrom("tiandeqing@ecode.net.cn");   
  122.         helper.setSubject("批量发送测试");   
  123.         helper.setText(html.toString(), true);   
  124.         // 添加内嵌文件,第1个参数为cid标识这个文件,第2个参数为资源   
  125.         helper.addInline("myimg"new File("D:\\My Documents\\My Pictures\\tian.JPG")); // 附件内容   
  126.         helper.addInline("vedio"new File("D:\\My Documents\\My Pictures\\vedio.JPG"));   
  127.         File file = new File("D:\\My Documents\\My Pictures\\hibernate框架.jpg");   
  128.         // 这里的方法调用和插入图片是不同的(插入到最后,并且直接显示),使用MimeUtility.encodeWord()来解决附件名称的中文问题   
  129.         helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);   
  130.         // 如果主题出现乱码,可以使用该函数,也可以使用下面的函数   
  131.         // helper.setSubject(MimeUtility.encodeText(String text,String   
  132.         // charset,String encoding))   
  133.         // 第2个参数表示字符集,第三个为目标编码格式。   
  134.         // MimeUtility.encodeWord(String word,String charset,String encoding)   
  135.         sender.send(msg);   
  136.         System.out.println("sendBatchEmail OK");   
  137.     }   
  138.   
  139.     /**  
  140.      * 集合转换字符串  
  141.      */  
  142.     public String getMailList(List<String> to) {   
  143.         StringBuffer toList = new StringBuffer();   
  144.         int length = to.size();   
  145.         if (to != null && length < 2) {   
  146.             toList.append(to.get(0));   
  147.         } else {   
  148.             for (int i = 0; i < length; i++) {   
  149.                 toList.append(to.get(i));   
  150.                 if (i != (length - 1)) {   
  151.                     toList.append(",");   
  152.                 }   
  153.             }   
  154.         }   
  155.         return toList.toString();   
  156.     }   
  157.   
  158.     // 通过模板构造邮件内容,参数content将替换模板文件中的${content}标签。   
  159.     private String getMailText(String content) throws Exception {   
  160.         String htmlText = "";   
  161.         // 通过指定模板名获取FreeMarker模板实例   
  162.         Template tpl = freeMarker.getConfiguration().getTemplate(   
  163.                 "registerUser.ftl");   
  164.         Map map = new HashMap(); // FreeMarker通过Map传递动态数据   
  165.         map.put("content", content); // 注意动态数据的key和模板标签中指定的属性相匹配   
  166.         // 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。   
  167.         htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);   
  168.         return htmlText;   
  169.     }   
  170. }  
 

 

3、模板文件src/mail/notify-mail.ftl

 
Text代码
  1. 欢迎加入!     
  2.      
  3. 亲爱的${username}     
  4.      
  5. 请点击链接完成注册:     
  6.      
  7. 如果您的email程序不支持链接点击,请将上面的地址拷贝至您的浏览器(如IE)的地址栏进入****。     
  8.      
  9. 您可以在***:     
  10.      
  11. 查看最新的影视资料,查看各种相关消费产品,在这里交友,灌水……;     
  12.      
  13. 希望您在**度过快乐的时光!     
  14.      
  15. -      
  16.      
  17. (这是一封自动产生的email,请勿回复。)    

  模板文件src/mail/registerUser.ftl

Txt代码
  1. <html>       
  2.    <head>       
  3.       <meta http-equiv="content-type" content="text/html;charset=utf8">       
  4.    </head>       
  5.    <body>       
  6.        恭喜您成功注册!您的用户名为:<font color='red' size='30'>${content}</font>       
  7.    </body>       
  8. </html>     
 

 

4、例子使用了FreeMarker。

FreeMarker就是一种用Java编写的模板引擎,它根据模板输出多种规格的文本。

特别指出的是,FreeMarker与Web应用框架无关,它同样可以应用在非Web应用程序环境中。

 程序目录结构:

 

 

注意在执行代码前,请确认已经将activation.jar,commons-logging-1.0.4.jar,mail.jar和spring.jar载入工程,并且服务器的25端口已开启。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
shiro安全框架扩展教程--如何动态控制页面节点元素的权限
freemarker报 java.io.FileNotFoundException:及Te...
Spring框架集成FreeMarker
freeMarker模板引擎将表格中的数据导出成Excel
java如何生成word文档_使用Java生成word文档(附源码)
如何能让Java生成复杂Word文档(1)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服