Springboot implements mail function: use thymeleaf template to send mail
1. Build a springboot project, import dependencies; application.properties configuration file, see
springboot send mail (1): send simple mail
To use the thymeleaf template, you need to add in 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 addedIf it is not added, an error will be reported.
2. Write the service interface and implement the class:
/** * Mail service interface * Created by ASUS on 2018/5/5 * * @Authod Grey Wolf */ public interface MailService { /** * Send html format emails * @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 class MailServiceImpl implements MailService { @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String form; /** * Send mail in html format * @param to recipient * @param subject * @param content */ @Override public void sendHtmlMail (String to , String subject , String content ) { MimeMessage message= mailSender .createMimeMessage() ; try { //true means that a multipart message needs to be created 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( "Successfully sent email in html format" ) ; } catch (Exception e){ System.out.println ( " Failed to send email in html format" ) ; } } }
3. Write the test class:
/** * Send mail test class * Created by ASUS on 5/5/2018 * * @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.测试效果:
我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。