SpringBoot使用Thymeleaf模板发送邮件信息

1.创建SpringBoot项目,引入thymeleaf模板和email依赖

        
            org.springframework.boot
            spring-boot-starter-mail
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

2.对邮箱进行配置

server:
  port: 8080
  servlet:
    context-path: /email

#配置邮箱信息
spring:
  mail:
    username: [email protected]
    password: xxxx  #授权码
    host: smtp.qq.com
    properties:
      smtp:
        ssl:
          enable: true
    default-encoding: UTF-8
后台代码
package com.email.demo.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @ClassName EmailController
 * @Description TODO
 * @Author lyp
 * @Date 2019/5/27 11:19
 * @Version 1.0
 */
@RestController
public class EmailController {

    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String sendEmail;

    /**
     *  获取html中的内容
     */
    private String build(String message) {
        Context context = new Context();
        context.setVariable("message", message);
        String result = templateEngine.process("send", context);
        System.out.println(result);
        return result;
    }

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public void sendMail(String email) throws MessagingException {
        String name = build("小乔");
        //创建一个发送复杂消息对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

        helper.setSubject("");
        //邮件内容,setText()第二个参数表示是否开启解析html
        helper.setText(name,true);

        helper.setFrom(sendEmail);
        helper.setTo(email);

        javaMailSender.send(mimeMessage);
    }
}

html页面



    


    
,欢迎来到王者峡谷!

你可能感兴趣的:(SpringBoot使用Thymeleaf模板发送邮件信息)