1. 程式人生 > >配置Spring發送郵件

配置Spring發送郵件

internet work inter tac sendemail red gravity 為我 reat

推薦查看原博客 轉載自:配置Spring發送郵件

Spring Email抽象的核心是MailSender接口。顧名思義,MailSender的實現能夠通過連接Email服務器實現郵件發送的功能。
技術分享圖片

Spring自帶的一個MailSender的實現——JavaMailSenderImpl。它會使用JavaMail API來發送Email。

配置郵件發送器

需要的核心maven:

     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.3.8.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>

配置bean:

public class RootConfig {

    /**
     * 配置郵件發送器
     * @return
     */
    @Bean
    public MailSender mailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.163.com");//指定用來發送Email的郵件服務器主機名
        mailSender.setPort(25);//默認端口,標準的SMTP端口
        mailSender.setUsername("[email protected]");//用戶名
        mailSender.setPassword("test");//密碼
        return mailSender;
    }

}

需要註意的是,如果你使用163等郵件服務器的話,一定要在設置中開啟SMTP。

裝配和使用郵件發送器

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RootConfig.class, WebConfig.class})
@WebAppConfiguration
public class EmailSenderTest {

    @Autowired
    private JavaMailSender mailSender;

    @Test
    public void sendSimpleEmail(){
        SimpleMailMessage message = new SimpleMailMessage();//消息構造器
        message.setFrom("[email protected]");//發件人
        message.setTo("[email protected]");//收件人
        message.setSubject("Spring Email Test");//主題
        message.setText("hello world!!");//正文
        mailSender.send(message);
        System.out.println("郵件發送完畢");
    }

}

下面是收到的郵件:
技術分享圖片

構建豐富內容的Email消息

添加附件

發送帶有附件的Email,關鍵技巧是創建multipart類型的消息——Email由多個部分組成,其中一部分是Email體,其他部分是附件。
為了發送multipart類型的Email,你需要創建一個MIME(Multipurpose Internet Mail Extensions)的消息。

/**
     * 發送帶有附件的email
     * @throws MessagingException 
     */
    @Test
    public void sendEmailWithAttachment() throws MessagingException{
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);//構造消息helper,第二個參數表明這個消息是multipart類型的
        helper.setFrom("[email protected]");
        helper.setTo("[email protected]");
        helper.setSubject("Spring Email Test");
        helper.setText("這是一個帶有附件的消息");
        //使用Spring的FileSystemResource來加載fox.png
        FileSystemResource image = new FileSystemResource("D:\\fox.png");
        System.out.println(image.exists());
        helper.addAttachment("fox.png", image);//添加附加,第一個參數為添加到Email中附件的名稱,第二個人參數是圖片資源
        mailSender.send(message);
        System.out.println("郵件發送完畢");
    }

javax.mail.internet.MimeMessage本身的API有些笨重。Spring為我們提供了MimeMessageHelper,來幫助我們,只需要將其實例化並將MimeMessage傳給其構造器。
結果:
技術分享圖片

發送富文本內容的Email

這裏我們使用嵌入式的圖片:

/**
     * 發送富文本內容的Email
     * @throws MessagingException 
     */
    @Test
    public void sendRichEmail() throws MessagingException{
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom("[email protected]");
        helper.setTo("[email protected]");
        helper.setSubject("Spring Email Test");
        helper.setText("<html><body><img src=‘cid:testLogo‘>"
                + "<h4>Hello World!!!</h4>"
                + "</body></html>", true);//第二個參數表明這是一個HTML
        //src=‘cid:testLogo‘表明在消息中會有一部分是圖片並以testLogo來進行標識
        ClassPathResource image = new ClassPathResource("logo.jpg");
        System.out.println(image.exists());
        helper.addInline("testLogo", image);//添加內聯圖片,第一個參數表明內聯圖片的標識符,第二個參數是圖片的資源引用
        mailSender.send(message);
    }

結果:
技術分享圖片

使用模板生成Email

使用Velocity構建Email消息

Apache Velocity是由Apache提供的通用的模板引擎。
配置VelocityEngine工廠bean,它能在Spring應用上下文中很便利的生成VelocityEngine:

/**
     * 配置VelocityEngine工廠Bean
     * @return
     */
    @Bean
    public VelocityEngineFactoryBean velocityEngine() {
        VelocityEngineFactoryBean velocityEngine = new VelocityEngineFactoryBean();
        Properties props = new Properties();
        props.setProperty("resource.loader", "class");
        props.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityEngine.setVelocityProperties(props);
        return velocityEngine;
    }

這裏我們將其配置為從類路徑下加載Velocity模板

使用:

@Autowired
    VelocityEngine velocityEngine;

    @SuppressWarnings("deprecation")
    @Test
    public void sendEmailByVelocity() throws MessagingException{
        Map<String, Object> modal = new HashMap<String, Object>();
        modal.put("name", "薛小強");
        modal.put("text", "這是一個用Velocity生成的模板");
        //使用VelocityEngineUtils將Velocity模板與模型數據合並成String
        String emailText = VelocityEngineUtils
                .mergeTemplateIntoString(velocityEngine, "emailTemplate.vm", "UTF-8", modal);

        MimeMessage message = mailSender.createMimeMessage();
        //第三個參數設置編碼,否則如果有漢字會出現亂碼問題
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
        helper.setFrom("[email protected]");
        helper.setTo("[email protected]");
        helper.setSubject("Spring Email Test");
        helper.setText(emailText, true);
        ClassPathResource image = new ClassPathResource("logo.jpg");
        helper.addInline("logo", image);
        mailSender.send(message);
        System.out.println("郵件發送完畢");
    }

這裏的模板emailTemplate.vm文件內容為:

<!DOCTYPE html>
<html>
<body>
<img src=‘cid:logo‘>
<h4>Hello ${name}</h4>
<h3>${text}</h3>
</body>
</html> 

結果:
技術分享圖片

配置Spring發送郵件