利用发送邮件SpringMail+thymeleaf+配置Bean实现


以QQ邮箱为例子。
1.确保smtp邮件服务开启,并获取密码
2.配置JavaBean的邮件发送器
3.测试

1.确保Stmp邮件服务开启,并获取密码
1.登录邮箱 >>> 设置>>> 账户
POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
开启smtp
2.配置JavaBean的邮件发送器

1) JavaMailConfig

package lb.springboot.config;

import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.servlet.ViewResolver;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;

@Configuration
@PropertySource("classpath:/exception.properties")
public class JavaMailConfig {

    private static final int PORT = 465;// 587/465

    @Autowired
    private Environment env;// 获取classpath下的 exception.properties 文件

    // 邮件发送器
    @Bean
    public JavaMailSender mailSender() {
        System.err.println("@@@@@@@@@JavaMailSender");
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(env.getProperty("mail.host"));
        mailSender.setProtocol(env.getProperty("mail.smtp"));
        mailSender.setUsername(env.getProperty("mail.username"));
        mailSender.setPassword(env.getProperty("mail.password"));
        mailSender.setPort(PORT);
        mailSender.setDefaultEncoding(env.getProperty("mail.defaultencodeing"));
        Properties prop = new Properties();
        // 设定properties
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.timeout", "25000");
        // 设置调试模式可以在控制台查看发送过程
        // prop.put("mail.debug", "true");
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        mailSender.setJavaMailProperties(prop);
        return mailSender;
    }

    // 模板视图解析器
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine springTemplateEngine)
    {
        System.err.println("@@@@@@@@@ViewResolver");
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(springTemplateEngine);
        return viewResolver;
    }
    // 模板解析器
    @Bean
    public ClassLoaderTemplateResolver emailTemplateResolver()
    {
        System.err.println("@@@@@@@@@ClassLoaderTemplateResolver");
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("mail/");
        resolver.setTemplateMode("HTML5");
        resolver.setOrder(1);
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }
    // 装配TemplateEngine
    @Bean
    public TemplateEngine templateEngine(TemplateResolver templateResolver)
    {
        System.err.println("@@@@@@@@@TemplateEngine");
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

}

2) exception.properties
#email
mail.host = smtp.qq.com
mail.smtp = smtp
mail.prot = smtp
mail.username = [email protected]
mail.password = xxxxxxxxx
mail.defaultencodeing = UTF-8
3)html模板 路径为: …\src\main\resources\mail


<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>hellotitle>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
head>
<body>
<p th:text="'Hello!, ' + ${hehe} + '!'" >p>
body>
html>

4)实现

@Autowired
protected JavaMailSender javaMailSender; 

@Autowired
protected TemplateEngine thymeleaf;

3.测试

    @RequestMapping("/sendTestEmail")
    public Object sendTestEmail(@RequestParam("messagepayload") String messagepayload) throws MessagingException {
        System.out.println(messagepayload);
        emailModeHtmlMail("[email protected]","emailmode","[email protected]");
        return messagepayload;
    }
   /**
     * 发送html邮件
     * @param to 收件人
     * @param subject 主题
     * @param strText 模板文本
     * @return
     */
    protected boolean emailModeHtmlMail(String to, String subject, String strText){
        boolean result = true;

        MimeMessage mailMessage = javaMailSender.createMimeMessage();  
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);  
        Context con = new Context();
        con.setVariable("hehe", strText);
        String emailtext = thymeleaf.process("emailmode.html", con);

        try {
            // 设置收件人,寄件人 用数组发送多个邮件
            messageHelper.setTo(to);
            messageHelper.setFrom(to);
            messageHelper.setSubject(subject);
            // true 表示启动HTML格式的邮件  
            messageHelper.setText(emailtext, true);  
            // 发送邮件
            javaMailSender.send(mailMessage);
        } catch (MessagingException e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }

————————————-过程难点
1.bean装配不太懂,邮件发送器 搞了很久都没有出来,结果发现 @bean 装配JavaMailSender ,@Autowired使用 JavaMailSender ,之前 @bean装配的一直是 MailSender
2.mail文件夹路径,工程获取的路径和我想象的不一样,导致我一直那么到模板,调了很久
3.ssl 需要注意
4.Environment 就随便试了一下就ok了,有待研究
————————————-推荐
该实例是利用 《Spring实战(第4版)》 编写出的,里面有对应的代码,如有疑问可阅读此书。

你可能感兴趣的:(个人知识管理)