栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot + Thymeleaf解析模板 发送邮件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot + Thymeleaf解析模板 发送邮件

1. 项目目录

2. 类Email 处理前端请求
@Controller
public class Email {

    private EmailService emailService;

    public Email(EmailService emailService) {
        this.emailService = emailService;
    }


    @GetMapping("/")
    public String index() {
        return "index";
    }

    @GetMapping("/sendEmail")
    public String sendEmail(String recipientEmail) throws MessagingException {
        emailService.sendEmail(recipientEmail);
        return "index";
    }
}
3. 类EmailService
@Service
public class EmailService {

    private JavaMailSenderImpl mailSender;
    private TemplateEngine templateEngine;

    public EmailService(JavaMailSenderImpl mailSender, SpringTemplateEngine templateEngine) {
        this.mailSender = mailSender;
        this.templateEngine = templateEngine;
    }

    public void sendEmail(String recipientEmail) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setSubject("Test Email");
        helper.setFrom("example@qq.com");
        helper.setTo(recipientEmail);

        Context ctx = new Context();
        ctx.setVariable("name", "JACK");
        String emailStr = templateEngine.process("stencil/emailTemplate", ctx);

        helper.setText(emailStr, true);
        mailSender.send(mimeMessage);
    }

}
thymeleaf一些问题
  1. 在包 package org.springframework.boot.autoconfigure.thymeleaf; 里的ThymeleafProperties类,默认定义了thymeleaf的前后缀。
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/845748.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号