SpringBoot配置Email發(fā)送功能
相信使用過Spring的眾多開發(fā)者都知道Spring提供了非常好用的 JavaMailSender
接口實(shí)現(xiàn)郵件發(fā)送溢陪。在Spring Boot的Starter模塊中也為此提供了自動(dòng)化配置萍虽。下面通過實(shí)例看看如何在Spring Boot中使用 JavaMailSender
發(fā)送郵件。
快速入門
在Spring Boot的工程中的 pom.xml
中引入 spring-boot-starter-mail
依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
如其他自動(dòng)化配置模塊一樣形真,在完成了依賴引入之后杉编,只需要在 application.properties
中配置相應(yīng)的屬性內(nèi)容超全。
下面我們以QQ郵箱為例,在 application.properties
中加入如下配置(注意替換自己的用戶名和密碼):
spring.mail.host=smtp.qq.com
spring.mail.username=用戶名 //發(fā)送方的郵箱
spring.mail.password=密碼 //對(duì)于qq郵箱而言 密碼指的就是發(fā)送方的授權(quán)碼
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true 注意:在spring.mail.password處的值是需要在郵箱設(shè)置里面生成的授權(quán)碼邓馒,這個(gè)不是真實(shí)的密碼嘶朱。
通過單元測(cè)試來實(shí)現(xiàn)一封簡(jiǎn)單郵件的發(fā)送:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
@Autowired
private JavaMailSender mailSender;
@Test
public void sendSimpleMail() throws Exception {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("dyc87112@qq.com");
message.setTo("dyc87112@qq.com");
message.setSubject("主題:簡(jiǎn)單郵件");
message.setText("測(cè)試郵件內(nèi)容");
mailSender.send(message);
}
}
到這里,一個(gè)簡(jiǎn)單的郵件發(fā)送就完成了光酣,運(yùn)行一下該單元測(cè)試疏遏,看看效果如何?
由于Spring Boot的starter模塊提供了自動(dòng)化配置救军,所以在引入了 spring-boot-starter-mail
依賴之后财异,會(huì)根據(jù)配置文件中的內(nèi)容去創(chuàng)建 JavaMailSender
實(shí)例,因此我們可以直接在需要使用的地方直接 @Autowired
來引入郵件發(fā)送對(duì)象唱遭。
對(duì)于qq郵箱這樣寫過后會(huì)報(bào)錯(cuò):
1戳寸、異常信息:
nested exception is:
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure. Failed messages: javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure; message exception details (1) are:
Failed message 1:
javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is:
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2046)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:711)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:421)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:307)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:296)
這種錯(cuò)誤一般是因?yàn)閖re的lib下C:\Program Files\Java\jdk1.8.0_51\jre\lib\security,替換2個(gè)jar包拷泽,參考文檔
http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
2疫鹊、異常信息
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:424)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:307)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:296)
at com.vcredit.ddcash.monitor.controller.AppTest.testSendSimple(AppTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
發(fā)送方必須要開啟smtp,獲取到的授權(quán)碼司致,界面如下:
3拆吆、異常信息:
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: STARTTLS is required but host does not support STARTTLS. Failed messages: javax.mail.MessagingException: STARTTLS is required but host does not support STARTTLS; message exception details (1) are:
Failed message 1:
javax.mail.MessagingException: STARTTLS is required but host does not support STARTTLS
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:721)
at javax.mail.Service.connect(Service.java:366)
at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:501)
at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:421)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:307)
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:296)
at com.vcredit.ddcash.monitor.controller.AppTest.testSendSimple(AppTest.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
換成公司企業(yè)郵箱報(bào)錯(cuò),通過將properties文件的內(nèi)容修改就可以了蚌吸,這里的用戶密碼就是自己的郵箱密碼(這點(diǎn)不同于qq郵箱)
1. 發(fā)送HTML格式的郵件
spring.mail.properties.mail.smtp.starttls.required=false```
@Test
public void testSendHtml() {
MimeMessage message = null;
try {
message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(username);
helper.setTo("398986099@qq.com");
helper.setSubject("標(biāo)題:發(fā)送Html內(nèi)容");
StringBuffer sb = new StringBuffer();
sb.append("<h1>大標(biāo)題-h1</h1>")
.append("<p style='color:#F00'>紅色字</p>")
.append("<p style='text-align:right'>右對(duì)齊</p>");
helper.setText(sb.toString(), true);
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(message);
}
注意:這里創(chuàng)建的是MimeMessageHelper
锈拨,且在調(diào)用setText
時(shí)需要在第二個(gè)參數(shù)傳入true
,這樣才會(huì)使用HTML格式發(fā)送郵件
通過velocity模板發(fā)送郵件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
</dependency>
@Autowired
private VelocityEngine velocityEngine;
@Test
public void sendTemplateMail() throws Exception {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("dingfuzhao@vcredit.com");
helper.setTo("dingfuzhao@vcredit.com");
helper.setSubject("主題:模板郵件");
Map<String, Object> model = new HashedMap();
model.put("username", "didi");
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "template.vm", "UTF-8", model);
helper.setText(text, true);
javaMailSender.send(mimeMessage);
}
在resources下建一個(gè)templates包 該包下建立一個(gè)文件template.vm羹唠,內(nèi)容以html格式隨便寫
<html>
<body>
<h3>你好奕枢, ${username}, 這是一封模板郵件!</h3>
</body>
</html>
測(cè)試結(jié)果: