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

Spring + Thymeleaf 发送邮件

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

Spring + Thymeleaf 发送邮件

1 Pom等未展示的内容

可见此处

2 EmailService 处理邮件逻辑
@Service
public class EmailService {


    private TemplateEngine emailTemplateEngine;

    public EmailService(SpringTemplateEngine emailTemplateEngine) {
        this.emailTemplateEngine = emailTemplateEngine;
    }

    public void sendEmail(String recipientName, String recipientEmail) throws MessagingException {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setUsername("example@qq.com");
        // qq独立密码
        mailSender.setPassword("---");
        mailSender.setHost("smtp.qq.com");
        Properties props = new Properties();
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", 587);
        // props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
        props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        props.put("mail.smtp.connectiontimeout", 20000);
        mailSender.setJavaMailProperties(props);

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        // 此处不加UTF-8,邮件里的中文会乱码
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
        helper.setSubject("Test email");
        helper.setFrom("example@qq.com");
        helper.setTo(recipientEmail);

        Context ctx = new Context();
        ctx.setVariable("name", recipientName);
        
        String processedText = emailTemplateEngine.process("email-template", ctx);
		
		// true = 邮件为html格式
        helper.setText(processedText, true);

        mailSender.send(mimeMessage);

    }
}
3 SpringMVC.xml 配置thymeleaf模板引擎

该模板引擎用于将html文件解析为String





    
        
            
                
                
                
                
                
                
            
        
    
4 用于生成String的模板HTML



    Template for HTML email with inline image
    



我是谁?

Regards,
The Thymeleaf Team

5 工程目录

路径的一些问题
  • TemplateResolver的prefix
    1. 加classpath:thymeleaf会到resources文件夹下找文件
    2. 不加classpath:thymeleaf会到webapp文件夹下找文件
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/852463.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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