springboot傳送郵件(5):使用thymeleaf模板傳送郵件
阿新 • • 發佈:2019-01-30
springboot實現郵件功能:使用thymeleaf模板傳送郵件
1.建springboot專案,匯入依賴;application.properties配置檔案,看
使用thymeleaf模板需要在application.properties新增:
# THYMELEAF (ThymeleafAutoConfiguration) spring.thymeleaf.check-template-location=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.excluded-view-names= # comma-separated list of view names that should be excluded from resolution如果不加,會報錯。spring.thymeleaf.view-names= # comma-separated list of view names that can be resolved spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
2.編寫服務介面,實現類:
/** * 郵件服務介面 * Created by ASUS on 2018/5/5* * @Authod Grey Wolf */ public interface MailService { /** * 傳送html格式的郵件 * @param to * @param subject * @param content */ void sendHtmlMail(String to,String subject,String content); }
/** * * 郵件服務類 * Created by ASUS on 2018/5/5 * * @Authod Grey Wolf */ @Service("mailService") public classMailServiceImpl implements MailService { @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String form; /** * 傳送html格式的郵件 * @param to 接受者 * @param subject 主題 * @param content 內容 */ @Override public void sendHtmlMail(String to, String subject, String content) { MimeMessage message=mailSender.createMimeMessage(); try { //true表示需要建立一個multipart message MimeMessageHelper helper=new MimeMessageHelper(message,true); helper.setFrom(form); helper.setTo(form); helper.setSubject(subject); helper.setText(content,true); mailSender.send(message); System.out.println("html格式郵件傳送成功"); }catch (Exception e){ System.out.println("html格式郵件傳送失敗"); } } }
3.編寫測試類:
/** * 傳送郵件測試類 * Created by ASUS on 2018/5/5 * * @Authod Grey Wolf */ @RunWith(SpringRunner.class) @SpringBootTest public class MailTest { @Autowired private MailService mailService; @Autowired private TemplateEngine templateEngine; @Value("${mail.fromMail.addr}") private String form; @Test public void sendTemplateMail() throws Exception{ //建立郵件正文 //是導這個包import org.thymeleaf.context.Context; Context context = new Context(); context.setVariable("username","Grey Wolf"); //獲取thymeleaf的html模板 String emailContent= templateEngine.process("template", context); mailService.sendHtmlMail(form,"這是thymeleaf模板郵件",emailContent); } }
4.測試效果:
我的座右銘:不會,我可以學;落後,我可以追趕;跌倒,我可以站起來;我一定行。