使用Spring JavaMailSender发送邮件

许多业务场景下需要给用户发送邮件,例如注册、重置密码等,Spring提供 JavaMailSender接口实现邮件发送。
本文对JavaMailSender用法做个简单的小结。

1. maven依赖

在pom.xml中添加如下依赖:


    4.3.6.RELEASE



    org.springframework
    spring-core
    ${springframework.version}


    org.springframework
    spring-context
    ${springframework.version}


    org.springframework
    spring-context-support
    ${springframework.version}


    org.springframework
    spring-beans
    ${springframework.version}



    javax.mail
    mail
    1.4.7

2.applicationContext.xml

applicationContext.xml




    
    
        
        
        
        
        
        
            
                true
                true
                true
            
        
    


3.测试代码

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.mail.internet.MimeMessage;
import java.io.File;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class JavaMailSenderTest {

    @Autowired
    private JavaMailSender javaMailSender;

    @Test
    public void testSimpleTextMail(){   //发送普通文本邮件

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("FX_SKY");// 发送者,可选的
        mailMessage.setTo("[email protected]");//接受者
        mailMessage.setSubject("测试邮件");//主题
        mailMessage.setText("Test Email send by javaMailSender!");//邮件内容

        javaMailSender.send(mailMessage);
    }

    @Test
    public void testMimeMail() throws Exception {   //发送HTML格式的邮件

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("FX_SKY");
        helper.setTo("[email protected]");
        helper.setSubject("主题:嵌入静态资源");
        helper.setText("", true);

        javaMailSender.send(mimeMessage);
    }

    @Test
    public void testMimeInlineMail() throws Exception { //发送HTML格式含图片的邮件

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("FX_SKY");
        helper.setTo("[email protected]");
        helper.setSubject("主题:嵌入静态资源");
        helper.setText("", true);
        FileSystemResource logoFile = new FileSystemResource(new File("logo.jpg"));
        helper.addInline("logo", logoFile);

        javaMailSender.send(mimeMessage);
    }

    @Test
    public void testAttachmentMail() throws Exception { //发送含附件的邮件

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);// 第二个参数设置为true,表示允许添加附件
        helper.setFrom("FX_SKY");
        helper.setTo("[email protected]");
        helper.setSubject("发送含图片附件的邮件");
        helper.setText("含有附件的邮件");

        helper.addAttachment(MimeUtility.encodeText("附件-1.jpg"), new File("E:/attachment1.jpg"));
        helper.addAttachment(MimeUtility.encodeText("附件-2.jpg"), new File("E:/attachment2.jpg"));

        javaMailSender.send(mimeMessage);
    }
}

模板邮件

通常我们使用邮件发送服务的时候,都会有一些固定的场景,比如重置密码、注册确认等,给每个用户发送的内容可能只有小部分是变化的。所以,很多时候我们会使用模板引擎来为各类邮件设置成模板,这样我们只需要在发送时去替换变化部分的参数即可。
Java中常用的模板引擎有 FreeMarker 和Velocity,下面我们以Velocity为例做演示。
pom.xml 引入velocity 依赖:

        
            org.apache.velocity
            velocity
            1.7
        
        
            org.apache.velocity
            velocity-tools
            2.0
        

在resources/templates/ 目录下,创建一个模板页面mail.vm:



    

你好, ${username}, 这是一封模板邮件!

点击激活: ${activation_url}

最后,我们在单元测试中加入发送模板邮件的测试用例,代码如下:

    @Test
    public void testSendTemplateMail() throws Exception {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom("FX_SKY");
        helper.setTo("[email protected]");
        helper.setSubject("主题:模板邮件");
        
        VelocityContext context = new VelocityContext();
        context.put("username", "Velocity");
        context.put("activation_url", "http://www.baidu.com");
        Template template = ve.getTemplate("templates/mail.vm");
        StringWriter sw = new StringWriter();
        template.merge(context, sw);
        
        String text = sw.toString();
        helper.setText(text, true);
        mailSender.send(mimeMessage);
    }

你可能感兴趣的:(使用Spring JavaMailSender发送邮件)