1.创建SpringBoot项目,引入thymeleaf模板和email依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.对邮箱进行配置
server:
port: 8080
servlet:
context-path: /email
#配置邮箱信息
spring:
mail:
username: xxxx@qq.com
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页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<span th:text="${message}"></span>
<span>,欢迎来到王者峡谷!</span>
</div>
</body>
</html>