1 . pom文件加入依赖
<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 . application.properties加入邮箱配置
spring.mail.host=邮件host(如:smtp.exmail.qq.com)
spring.mail.username=用户名
spring.mail.password=密码
spring.mail.default-encoding=UTF-8
3 . 发送邮件代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* @author:
* @create:
**/
@Slf4j
@Component
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String from;
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
log.info("简单邮件发送成功。");
} catch (Exception e) {
log.error("发送简单邮件时发生异常!", e);
}
}
public void sendHtmlMail(String to, String subject, String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
log.info("html邮件发送成功");
} catch (MessagingException e) {
log.error("发送html邮件时发生异常!", e);
}
}
public void sendMailUseTemp(WarnBatchDto warnBatchDto) {
//创建邮件正文
Context context = new Context();
context.setVariable("name", warnBatchDto.getNickname());
context.setVariable("gender", warnBatchDto.getGender());
String emailContent = templateEngine.process("warnTemplate", context);
sendHtmlMail(warnBatchDto.getEmail(), "测试", emailContent);
}
}
4 . 模版文件
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
尊敬的<span th:text="${name}"></span>
<span th:switch="${gender}">
<span th:case="0"></span>
<span th:case="1">先生</span>
<span th:case="2">女士</span>
</span>:<br/>
您好<br/>
</body>
</html>
参考:http://www.ityouknow.com/springboot/2017/05/06/springboot-mail.html