使用Spring的JAVA Mail支持简化邮件发送

来源:互联网 发布:数据库概要设计 编辑:程序博客网 时间:2024/06/05 18:42

使用Spring的JAVA Mail支持简化邮件发送

闲来无事,翻看《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容器初始化):

public class SpringMailSender {
 
    // Spring的邮件工具类,实现了MailSender和JavaMailSender接口
    private JavaMailSenderImpl mailSender;
     
    public SpringMailSender() {
    // 初始化JavaMailSenderImpl,当然推荐在spring配置文件中配置,这里是为了简单
    mailSender = new JavaMailSenderImpl();
    // 设置参数
    mailSender.setHost("smtp.qq.com");
    mailSender.setUsername("mosaic@qq.com");
    mailSender.setPassword("asterisks");
    ...

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

1、发送简单邮件

/**
 * 简单邮件发送
 *
 */
public void simpleSend() {
    // 构建简单邮件对象,见名知意
    SimpleMailMessage smm = new SimpleMailMessage();
    // 设定邮件参数
    smm.setFrom(mailSender.getUsername());
    smm.setTo("mosaic@126.com");
    smm.setSubject("Hello world");
    smm.setText("Hello world via spring mail sender");
    // 发送邮件
    mailSender.send(smm);
}

  

2、发送带附件的邮件

/**
 * 带附件的邮件发送
 *
 * @throws MessagingException
 */
public void attachedSend()throws MessagingException {
    //使用JavaMail的MimeMessage,支付更加复杂的邮件格式和内容
    MimeMessage msg = mailSender.createMimeMessage();
    //创建MimeMessageHelper对象,处理MimeMessage的辅助类
    MimeMessageHelper helper = new MimeMessageHelper(msg,true);
    //使用辅助类MimeMessage设定参数
    helper.setFrom(mailSender.getUsername());
    helper.setTo("mosaic@126.com");
    helper.setSubject("Hello Attachment");
    helper.setText("This is a mail with attachment");
    //加载文件资源,作为附件
    ClassPathResource file = new ClassPathResource(
            "Chrysanthemum.jpg");
    //加入附件
    helper.addAttachment("attachment.jpg", file);
    //发送邮件
    mailSender.send(msg);
}

  

3、发送富文本邮件 

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

 

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

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

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

...
private VelocityEngine velocityEngine;
 
public SpringMailSender() {
        ...
    // Velocity的参数,通过VelocityEngineFactoryBean创建VelocityEngine,也是推荐在配置文件中配置的
    Properties props = System.getProperties();
    props.put("resource.loader","class");
    props
            .put("class.resource.loader.class",
                    "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    VelocityEngineFactoryBean v = new VelocityEngineFactoryBean();
    v.setVelocityProperties(props);
    try {
        velocityEngine = v.createVelocityEngine();
    }catch (VelocityException e) {
        e.printStackTrace();
    }catch (IOException e) {
        e.printStackTrace();
    }
 
}

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

<html>
<head>
<style type="text/css">
h4{
    color:red;
    background:#efefef;
}
</style>
</head>
<body>
<h4>${user} </h4>
<p><p>
<i>${content}</i>
</body>
</html>

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

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

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

 

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

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 一岁宝宝吐奶怎么办 一个月宝宝吐奶怎么办 2个月里小孩好哭怎么办 两个月宝宝闹觉怎么办 6岁儿童视力0.5怎么办 单一的三系减少怎么办 血小板低到50该怎么办 放化疗后白细胞低怎么办 化疗后白细胞低发烧怎么办 全程c反应蛋白高怎么办 儿童c反应蛋白高怎么办 c反应蛋白高是怎么办 新生儿c反蛋白高怎么办 c反应蛋白高发烧怎么办 血沉高到50了怎么办啊 血沉和超敏偏高怎么办 孕37周血糖偏高怎么办 孕37周血糖7.0多怎么办 孕妇超敏crp偏高怎么办 高敏c反应蛋白高怎么办 孕17周尿蛋白高怎么办 血小板低到20该怎么办 血象高发烧39度怎么办 新生儿血象3万多怎么办 血象高发烧不退怎么办 半岁宝宝血象高怎么办 5-6小孩免疫力差怎么办 快速c反应蛋白高怎么办 15个月宝宝发烧怎么办 小孩发烧到40度怎么办 孩子发烧到39度怎么办 宝宝抵抗力差总生病怎么办 献血前没休息好怎么办 拔了牙齿一直流血怎么办 拔牙后血块掉了怎么办 生血功能不强怎么办 孕妇白球比偏低怎么办 凝血因子Ⅷ很高怎么办 怀孕一个月上火了怎么办 38周了还没入盆怎么办 妊娠33周血压高怎么办