1.創(chuàng)建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 #授權(quán)碼
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中的內(nèi)容
*/
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("小喬");
//創(chuàng)建一個發(fā)送復(fù)雜消息對象
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
helper.setSubject("");
//郵件內(nèi)容,setText()第二個參數(shù)表示是否開啟解析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>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者