用Spring让Java Mail支持简化邮件发送

开发 后端
今天我们谈到Spring提供的邮件发送不仅支持简单邮件的发送、添加附件,而且还可以使用velocity模板控制页面样式。

  闲来无事,翻看《Spring in Action》,发现Spring集成了对JAVA Mail的支持,有点小激动的看了一遍,嗯,话说真的简单了很多。

  Spring的邮件发送的核心是MailSender接口,在Spring3.0中提供了一个实现类JavaMailSenderImpl,这个类是发送邮件的核心类。可以通过在配置文件中配置使用,当然也可以自己硬编码到代码中(方便起见,下面的演示代码都是硬编码到代码中,省得配置麻烦)。

  Spring提供的邮件发送不仅支持简单邮件的发送、添加附件,而且还可以使用velocity模板控制页面样式(应该也支持freemarker)。

  首先对加入相应Spring jar包和Java Mail 的jar包。

  我们首先得声明一个MailSender对象,因为MailSender对象只有两个重载的send(...)方法,显得有些简陋,我们建议选用JavaMailSender接口,或者干脆直接使用实现类,JavaMailSenderImpl。笔者是使用的JavaMailSenderImpl对象,功能丰富。

  声明JavaMailSenderImpl对象,并在构造函数中初始化(当然也可以使用IoC容器初始化):

  1.   public class SpringMailSender {  
  2.   // Spring的邮件工具类,实现了MailSender和JavaMailSender接口  
  3.   private JavaMailSenderImpl mailSender;  
  4.   public SpringMailSender() {  
  5.   // 初始化JavaMailSenderImpl,当然推荐在spring配置文件中配置,这里是为了简单  
  6.   mailSender = new JavaMailSenderImpl();  
  7.   // 设置参数  
  8.   mailSender.setHost("smtp.qq.com");  
  9.   mailSender.setUsername("786553789@qq.com");  
  10.   mailSender.setPassword("556WULI779");  
  11.   ... 

  得到了MailSender对象之后,就可以发送邮件了,下面是示例代码,没有封装,仅供参考。

  1、发送简单邮件

  1.   /**  
  2.   * 简单邮件发送  
  3.   *  
  4.   */ 
  5.   public void simpleSend() {  
  6.   // 构建简单邮件对象,见名知意  
  7.   SimpleMailMessage smm = new SimpleMailMessage();  
  8.   // 设定邮件参数  
  9.   smm.setFrom(mailSender.getUsername());  
  10.   smm.setTo("mosaic@126.com");  
  11.   smm.setSubject("Hello world");  
  12.   smm.setText("Hello world via spring mail sender");  
  13.   // 发送邮件  
  14.   mailSender.send(smm);  
  15.   } 

  2、发送带附件的邮件

  1.   /**  
  2.   * 带附件的邮件发送  
  3.   *  
  4.   * @throws MessagingException  
  5.   */ 
  6.   public void attachedSend() throws MessagingException {  
  7.   //使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容  
  8.   MimeMessage msg = mailSender.createMimeMessage();  
  9.   //创建MimeMessageHelper对象,处理MimeMessage的辅助类  
  10.   MimeMessageHelper helper = new MimeMessageHelper(msg, true);  
  11.   //使用辅助类MimeMessage设定参数  
  12.   helper.setFrom(mailSender.getUsername());  
  13.   helper.setTo("mosaic@126.com");  
  14.   helper.setSubject("Hello Attachment");  
  15.   helper.setText("This is a mail with attachment");  
  16.   //加载文件资源,作为附件  
  17.   ClassPathResource file = new ClassPathResource(  
  18.   "Chrysanthemum.jpg");  
  19.   //加入附件  
  20.   helper.addAttachment("attachment.jpg", file);  
  21.   //发送邮件  
  22.   mailSender.send(msg);  
  23.   } 

  3、发送富文本邮件

  1.   /**发送富文本邮件  
  2.   * @throws MessagingException  
  3.   */ 
  4.   public void richContentSend() throws MessagingException {  
  5.   MimeMessage msg = mailSender.createMimeMessage();  
  6.   MimeMessageHelper helper = new MimeMessageHelper(msg, true);  
  7.   helper.setFrom(mailSender.getUsername());  
  8.   helper.setTo("mosaic@126.com");  
  9.   helper.setSubject("Rich content mail");  
  10.   //第二个参数true,表示text的内容为html,然后注意<img/>标签,src='cid:file',
  11. 'cid'是contentId的缩写,'file'是一个标记,
  12. 需要在后面的代码中调用MimeMessageHelper的addInline方法替代成文件  
  13.   helper.setText(  
  14.   "<body><p>Hello Html Email</p><img src='cid:file'/></body>",  
  15.   true);  
  16.   FileSystemResource file = new FileSystemResource(  
  17.   "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");  
  18.   helper.addInline("file", file);  
  19.   mailSender.send(msg);  
  20.   } 

  4、使用Velocity模板确定邮件风格

  使用Velocity模板,需要Velocity的jar包,可以在官方网站下载,并加入ClassPath,然后需要声明一个VelocityEngine对象,具体的参考下面代码,这是笔者***次使用Velocity,不甚了解,言多有失,望见谅。

  声明一个VelocityEngine对象,并在构造函数中初始化(IoC is optional)

  1.   ...  
  2.   private VelocityEngine velocityEngine;  
  3.   public SpringMailSender() {  
  4.   ...  
  5.   // Velocity的参数,通过VelocityEngineFactoryBean创建VelocityEngine,也是推荐在配置文件中配置的  
  6.   Properties props = System.getProperties();  
  7.   props.put("resource.loader""class");  
  8.   props  
  9.   .put("class.resource.loader.class",  
  10.  "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");  
  11.   VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();  
  12.   v.setVelocityProperties(props);  
  13.   try {  
  14.   velocityEngine = v.createVelocityEngine();  
  15.   } catch (VelocityException e) {  
  16.   e.printStackTrace();  
  17.   } catch (IOException e) {  
  18.   e.printStackTrace();  
  19.   }  
  20.   } 

  简单的Velocity模板文件(index.vm):

  1.   <html> 
  2.   <head> 
  3.   <style type="text/css"> 
  4.   h4{  
  5.   color:red;  
  6.   background:#efefef;  
  7.   }  
  8.   </style> 
  9.   </head> 
  10.   <body> 
  11.   <h4>${user} </h4> 
  12.   <p><p> 
  13.   <i>${content}</i> 
  14.   </body> 
  15.   </html> 

  开起来貌似很容易理解,只是普通的Html文件,使用了一些${placeholder}作为占位符。

  Java要做的,就是加载模板,并将相应的值插入到占位符当中。

  1.   /**  
  2.   * 使用Velocity模板发送邮件  
  3.   *  
  4.   * @throws MessagingException  
  5.   */ 
  6.   public void templateSend() throws MessagingException {  
  7.   // 声明Map对象,并填入用来填充模板文件的键值对  
  8.   Map<String, String> model = new HashMap<String, String>();  
  9.   model.put("user""MZULE");  
  10.   model.put("content""Hello");  
  11.   // Spring提供的VelocityEngineUtils将模板进行数据填充,并转换成普通的String对象  
  12.   String emailText = VelocityEngineUtils.mergeTemplateIntoString(  
  13.   velocityEngine, "index.vm", model);  
  14.   // 和上面一样的发送邮件的工作  
  15.   MimeMessage msg = mailSender.createMimeMessage();  
  16.   MimeMessageHelper helper = new MimeMessageHelper(msg, true);  
  17.   helper.setFrom(mailSender.getUsername());  
  18.   helper.setTo("mosaic@126.com");  
  19.   helper.setSubject("Rich content mail");  
  20.   helper.setText(emailText, true);  
  21.  mailSender.send(msg);  
  22.   } 

  Spring可谓是大大简化了邮件的发送步骤,虽然我们自己封装可能实现起来并不复杂,但是,有现成的有何必要重新造轮子呢?(当然造轮子可以学到很多)

原文链接:http://www.cnblogs.com/codeplus/archive/2011/11/03/2232893.html

【编辑推荐】

  1. 深入Java,初探JVM
  2. struts2国际化小结
  3. 说说Maven项目搭建及常用包添加
  4. 电影《Java风云》预告片
责任编辑:彭凡 来源: 博客园
相关推荐

2009-12-09 15:23:36

PHP mail()函

2011-08-22 15:50:05

Linuxmailsendmail

2011-01-21 16:40:58

NagiosSendmail

2017-09-06 10:14:29

Nginx TCPmail邮件

2009-12-02 18:16:35

PHP mail发送邮

2021-06-11 06:54:34

程序邮件Django

2020-08-05 08:30:25

Spring BootJavaSE代码

2022-02-16 10:59:54

Spring端口邮件

2011-01-21 13:41:09

Sendmail

2011-01-21 13:56:44

SendmailSolaris

2015-02-10 18:18:36

U-Mail邮件服务器效率

2009-08-04 09:39:11

2024-03-25 08:45:18

邮件发送Spring应用程序

2012-02-29 09:19:30

ChromeGmail

2017-04-26 09:00:23

Python发送邮件脚本

2009-07-15 09:06:07

BeanTableMoSwing

2019-09-20 13:48:23

BashLinux命令

2022-01-28 15:04:57

Python日志邮件

2014-09-16 09:48:39

U-Mail邮件系统垃圾邮件

2009-06-17 14:10:30

Spring配置文件
点赞
收藏

51CTO技术栈公众号