Spring Boot 邮件发送
依赖配置
build.gradle
// 添加邮件依赖
compile('org.springframework.boot:spring-boot-starter-mail')
// 用于处理邮件模版
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
邮件服务器配置
以下是邮件相关配置项说明
# Email (MailProperties)
spring.mail.default-encoding=UTF-8 # Default MimeMessage encoding.
spring.mail.host= # SMTP server host. For instance, `smtp.example.com`.
spring.mail.jndi-name= # Session JNDI name. When set, takes precedence over other mail settings.
spring.mail.password= # Login password of the SMTP server.
spring.mail.port= # SMTP server port.
spring.mail.properties.*= # Additional JavaMail session properties.
spring.mail.protocol=smtp # Protocol used by the SMTP server.
spring.mail.test-connection=false # Whether to test that the mail server is available on startup.
spring.mail.username= # Login user of the SMTP server.
以下是实际配置(注意:当服务器使用SSL加密时,最后一行是必须的)
spring:
mail:
host: smtp.exmail.qq.com
port: 465
protocol: smtp
username: <username>
password: <password>
properties:
mail:
smtp:
auth: true
socketFactory.class: javax.net.ssl.SSLSocketFactory
Thymeleaf配置
以下是Thymeleaf的配置项说明
spring.thymeleaf.cache – enable/disable template caching.
spring.thymeleaf.check-template – check that the template exists before rendering it.
spring.thymeleaf.check-template-location – check that the templates location exists.
spring.thymeleaf.content-type – specifies content-type value.
spring.thymeleaf.enabled – enable mvc thymeleaf view resolution.
spring.thymeleaf.encoding – specifies template encoding.
spring.thymeleaf.excluded-view-names – comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.mode – template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.prefix – specifies the prefix that gets prepended to view names when building a URL.
spring.thymeleaf.suffix – specifies the suffix that gets appended to view names when building a URL.
spring.thymeleaf.template-resolver-order – specifies the order of the template resolver in the chain.
spring.thymeleaf.view-names – comma-separated list of view names that can be resolved.
也可以使用java代码进行配置
@Configuration
public class ThymeleafConfig {
@Bean
public SpringTemplateEngine springTemplateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(htmlTemplateResolver());
return templateEngine;
}
@Bean
public SpringResourceTemplateResolver htmlTemplateResolver(){
SpringResourceTemplateResolver emailTemplateResolver = new SpringResourceTemplateResolver();
emailTemplateResolver.setPrefix("classpath:/templates/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode(StandardTemplateModeHandlers.HTML5.getTemplateModeName());
emailTemplateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
return emailTemplateResolver;
}
}
发送邮件
@Component
public class MailHelper {
@Value("${mail.from}")
private String from;
@Value("${mail.nickname}")
private String nickname;
@Autowired
private JavaMailSender mailSender;
@Autowired
private SpringTemplateEngine templateEngine;
/**
* 发送纯文本内容
* @param to
* @param title
* @param text
* @throws MessagingException
*/
public void sendTextMail(String to, String title, String text) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false,"UTF-8");
try {
helper.setFrom(new InternetAddress(from, nickname, "UTF-8"));
} catch (UnsupportedEncodingException e){
helper.setFrom(from);
}
helper.setTo(to);
helper.setSubject(title);
helper.setText(text);
mailSender.send(mimeMessage);
}
/**
* 发送模版邮件
* @param to
* @param title
* @param templateName
* @param data
* @param files
* @throws MessagingException
*/
public void sendTemplateMail(String to, String title, String templateName, Map data, Map<String, String> files) throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
Context context = new Context();
context.setVariables(data);
String html = templateEngine.process(templateName, context);
try {
helper.setFrom(new InternetAddress(from, nickname, "UTF-8"));
} catch (UnsupportedEncodingException e){
helper.setFrom(from);
}
helper.setTo(to);
helper.setSubject(title);
helper.setText(html, true);
if (null != files){
for(String name: files.keySet()){
ClassPathResource file = new ClassPathResource(files.get(name));
helper.addInline(name, file); // 内联图片
// helper.addAttachment(name, file); // 添加附件
}
}
mailSender.send(mimeMessage);
}
}
Thymeleaf 模版
Thymeleaf模版的使用网上教程很多,这里放一个示例。
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>
<link rel="stylesheet" th:href="@{/css/main.css}"/>
<title>Getting Started: Serving Web Content</title>
</head>
<body>
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<img th:src="@{/img/logo.png}" alt="memorynotfound logo"/>
</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1>Spring Boot Thymeleaf Configuration Example</h1>
<h2 th:text="${message}"></h2>
</div>
</div>
<!-- include javascript -->
<script type="text/javascript" src="webjars/jquery/3.2.1/jquery.min.js/"></script>
<script type="text/javascript" src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
如果在邮件中使用内联图片,图片的src
属性需要按如下代码设置
<img src="cid:facebook" height="28" alt="facebook" />
其中cid
的值是MimeMessageHelper.addInline()
方法第一个参数的值。
参考:
Sending Email](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-email.html))
Appendix A. Common application properties](https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html))
Spring Boot Thymeleaf Configuration Example - Memorynotfound