發送郵件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
spring
mail:
default-encoding: UTF-8
host: smtp.qq.com
username: [email protected]
password: 1234567890
port: 22
protocol: smtp
properties:
mail:
smtp:
ssl:
enable: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
@Service
public class EmailUtil {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String from;
@Async
public void sendEmail(Context context, String templateName, String to, String [] cc,
String subject, String text, List<String> attachmentList){
try {
System.setProperty("mail.mime.splitlongparameters", "false");
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper;
helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
if(cc != null && cc.length > 0){
helper.setCc(cc);
}
if(context != null && StringUtils.isNotBlank(templateName)){
String emailContent = templateEngine.process(templateName, context);
helper.setText(emailContent, true);
}else{
helper.setText(text);
}
if(attachmentList != null && attachmentList.size() > 0){
for (String attachment : attachmentList) {
FileSystemResource file = new FileSystemResource(attachment);
helper.addAttachment(file.getFilename(), file);
}
}
mailSender.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
- 配置發送郵件的模板
在resources目錄下創建templates目錄。創建email.html模板。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>yimcarson</title>
<style>
body {
text-align: center;
margin-left: auto;
margin-right: auto;
}
#main {
text-align: center;
}
</style>
</head>
<body>
<div id="main">
<h3>Welcome <span th:text="${project}"></span> -By <span th:text=" ${author}"></span></h3>
Your Verification Code is
<h2><span th:text="${code}"></span></h2>
</div>
</body>
</html>