金闪闪女体化本子:Spring发送邮件简单实例dddd

来源:百度文库 编辑:九乡新闻网 时间:2024/05/06 04:08:15

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

Xml代码
  1.  id="mailSender"  
  2.     class="org.springframework.mail.javamail.JavaMailSenderImpl">  
  3.      name="host" value="222.173.82.207">  
  4.      name="javaMailProperties">  
  5.           
  6.              key="mail.smtp.auth">true  
  7.              key="mail.smtp.timeout">25000  
  8.           
  9.       
  10.      name="username" value="tiandeqing@ecode.net.cn" />  
  11.      name="password" value="密码" />  
  12.   
  13.  id="freeMarker"  
  14.     class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
  15.      name="templateLoaderPath" value="classpath:mail" />  
  16.      name="freemarkerSettings">  
  17.           
  18.              key="template_update_delay">1800  
  19.              key="default_encoding">UTF-8  
  20.              key="locale">zh_CN  
  21.           
  22.       
  23.   
 

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("");   
  105.         html.append("");   
  106.         html.append("");   
  107.         html.append("");   
  108.         html.append("");   
  109.         html.append("
    ");   
  110.         html.append("

    你好,Jarry

    "
    ).append(content);   
  111.         html.append("");//显示图片   
  112.         html.append("

    logo:");   

  113.         html.append("");   
  114.         html.append("
  115. ");   
  116.         html.append("");   
  117.         html.append("");   
  118.            
  119.         String toList = getMailList(address);   
  120.         InternetAddress[] iaToList = new InternetAddress().parse(toList);   
  121.         msg.setRecipients(Message.RecipientType.TO, iaToList);   
  122.         helper.setFrom("tiandeqing@ecode.net.cn");   
  123.         helper.setSubject("批量发送测试");   
  124.         helper.setText(html.toString(), true);   
  125.         // 添加内嵌文件,第1个参数为cid标识这个文件,第2个参数为资源   
  126.         helper.addInline("myimg"new File("D:\\My Documents\\My Pictures\\tian.JPG")); // 附件内容   
  127.         helper.addInline("vedio"new File("D:\\My Documents\\My Pictures\\vedio.JPG"));   
  128.         File file = new File("D:\\My Documents\\My Pictures\\hibernate框架.jpg");   
  129.         // 这里的方法调用和插入图片是不同的(插入到最后,并且直接显示),使用MimeUtility.encodeWord()来解决附件名称的中文问题   
  130.         helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);   
  131.         // 如果主题出现乱码,可以使用该函数,也可以使用下面的函数   
  132.         // helper.setSubject(MimeUtility.encodeText(String text,String   
  133.         // charset,String encoding))   
  134.         // 第2个参数表示字符集,第三个为目标编码格式。   
  135.         // MimeUtility.encodeWord(String word,String charset,String encoding)   
  136.         sender.send(msg);   
  137.         System.out.println("sendBatchEmail OK");   
  138.     }   
  139.   
  140.     /**  
  141.      * 集合转换字符串  
  142.      */  
  143.     public String getMailList(List to) {   
  144.         StringBuffer toList = new StringBuffer();   
  145.         int length = to.size();   
  146.         if (to != null && length < 2) {   
  147.             toList.append(to.get(0));   
  148.         } else {   
  149.             for (int i = 0; i < length; i++) {   
  150.                 toList.append(to.get(i));   
  151.                 if (i != (length - 1)) {   
  152.                     toList.append(",");   
  153.                 }   
  154.             }   
  155.         }   
  156.         return toList.toString();   
  157.     }   
  158.   
  159.     // 通过模板构造邮件内容,参数content将替换模板文件中的${content}标签。   
  160.     private String getMailText(String content) throws Exception {   
  161.         String htmlText = "";   
  162.         // 通过指定模板名获取FreeMarker模板实例   
  163.         Template tpl = freeMarker.getConfiguration().getTemplate(   
  164.                 "registerUser.ftl");   
  165.         Map map = new HashMap(); // FreeMarker通过Map传递动态数据   
  166.         map.put("content", content); // 注意动态数据的key和模板标签中指定的属性相匹配   
  167.         // 解析模板并替换动态数据,最终content将替换模板文件中的${content}标签。   
  168.         htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(tpl, map);   
  169.         return htmlText;   
  170.     }   
  171. }  
 

 

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.        
  2.           
  3.       "content-type" content="text/html;charset=utf8">       
  4.           
  5.           
  6.        恭喜您成功注册!您的用户名为:'red' size='30'>${content}       
  7.           
  8.      
 

 

4、例子使用了FreeMarker。

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

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

 程序目录结构:

 

 

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