Spring Boot 郵件發(fā)送
依賴配置
build.gradle
// 添加郵件依賴
compile('org.springframework.boot:spring-boot-starter-mail')
// 用于處理郵件模版
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
郵件服務(wù)器配置
以下是郵件相關(guān)配置項說明
# 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.
以下是實際配置(注意:當(dāng)服務(wù)器使用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代碼進(jìn)行配置
@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;
}
}
發(fā)送郵件
@Component
public class MailHelper {
@Value("${mail.from}")
private String from;
@Value("${mail.nickname}")
private String nickname;
@Autowired
private JavaMailSender mailSender;
@Autowired
private SpringTemplateEngine templateEngine;
/**
* 發(fā)送純文本內(nèi)容
* @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);
}
/**
* 發(fā)送模版郵件
* @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); // 內(nèi)聯(lián)圖片
// helper.addAttachment(name, file); // 添加附件
}
}
mailSender.send(mimeMessage);
}
}
Thymeleaf 模版
Thymeleaf模版的使用網(wǎng)上教程很多,這里放一個示例。
<!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>
如果在郵件中使用內(nèi)聯(lián)圖片浪感,圖片的src
屬性需要按如下代碼設(shè)置
<img src="cid:facebook" height="28" alt="facebook" />
其中cid
的值是MimeMessageHelper.addInline()
方法第一個參數(shù)的值昔头。
參考:
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