springboot 發送郵件+模板+附件

package com.example.demo;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.core.io.FileSystemResource;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.mail.javamail.MimeMessageHelper;import org.springframework.test.context.junit4.SpringRunner;import org.thymeleaf.TemplateEngine;import org.thymeleaf.context.Context;import org.thymeleaf.context.IContext;import javax.mail.MessagingException;import javax.mail.internet.MimeMessage;@RunWith(SpringRunner.class)@SpringBootTestpublic class SendMailWithTemplate {    @Autowired    JavaMailSender javaMailSender;    @Autowired    TemplateEngine templateEngine;    @Test    public void sendMailWithTempalte() throws MessagingException {        MimeMessage mailMessage = javaMailSender.createMimeMessage();        //開啓帶附件true        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);        // 聲明一個上下文對象,裏面放入要存到模板裏面的數據        IContext context = new Context();        //獲取模板html代碼        ((Context) context).setVariable("username", "alex");        // 指定相應的模板,而後給context數據傳過去        String process = templateEngine.process("index", context);        try {            messageHelper.setFrom("wangzhilei@jd.com");            messageHelper.setTo("wangzhilei@jd.com");            // 抄送//            String[] mails= new String[]{};//            messageHelper.setCc(mails);            // 密送 //            messageHelper.setBcc();            messageHelper.setSubject("tempalte 模板郵件");            // 設置處理好的結果,本質就是讀取內容而後 後面一個參數html:true必須爲true,保證正常的讀取hml            messageHelper.setText(process, true);            // 發送模板的時候,同時帶附件過去            FileSystemResource fileSystemResource = new FileSystemResource("src/main/resources/static/images/a.jpg");            messageHelper.addAttachment("b.jpg", fileSystemResource);        } catch (MessagingException e) {            e.printStackTrace();        }        javaMailSender.send(mailMessage);    }}
相關文章
相關標籤/搜索