相信使用過Spring的衆多開發者都知道Spring提供了很是好用的 JavaMailSender
接口實現郵件發送。在Spring Boot的Starter模塊中也爲此提供了自動化配置。下面經過實例看看如何在Spring Boot中使用 JavaMailSender
發送郵件。html
在Spring Boot的工程中的 pom.xml
中引入 spring-boot-starter-mail
依賴:java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
如其餘自動化配置模塊同樣,在完成了依賴引入以後,只須要在 application.properties
中配置相應的屬性內容。spring
下面咱們以QQ郵箱爲例,在 application.properties
中加入以下配置(注意替換本身的用戶名和密碼):oracle
spring.mail.host=smtp.qq.com
spring.mail.username=用戶名 //發送方的郵箱
spring.mail.password=密碼 //對於qq郵箱而言 密碼指的就是發送方的受權碼
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
處的值是須要在郵箱設置裏面生成的受權碼
,這個不是真實的密碼。 spring.mail.password受權碼
經過單元測試來實現一封簡單郵件的發送:app
@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("主題:簡單郵件"); message.setText("測試郵件內容"); mailSender.send(message); } }
到這裏,一個簡單的郵件發送就完成了,運行一下該單元測試,看看效果如何?socket
因爲Spring Boot的starter模塊提供了自動化配置,因此在引入了 spring-boot-starter-mail
依賴以後,會根據配置文件中的內容去建立 JavaMailSender
實例,所以咱們能夠直接在須要使用的地方直接 @Autowired
來引入郵件發送對象。spring-boot
對於qq郵箱這樣寫事後會報錯:單元測試
一、異常信息:測試
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is javax.mail.MessagingException: Could not convert socket to TLS;
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)ui
這種錯誤通常是由於jre的lib下C:\Program Files\Java\jdk1.8.0_51\jre\lib\security,替換2個jar包,參考文檔
http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
二、異常信息
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 Error: ??ê1ó?êúè¨??μ????£?ê?é???′: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
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)
發送方必需要開啓smtp,獲取到的受權碼,界面以下:
三、異常信息:
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)
換成公司企業郵箱報錯,經過將properties文件的內容修改就能夠了,這裏的用戶密碼就是本身的郵箱密碼(這點不一樣於qq郵箱)
spring.mail.properties.mail.smtp.starttls.enable=false
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("標題:發送Html內容"); StringBuffer sb = new StringBuffer(); sb.append("<h1>大標題-h1</h1>") .append("<p style='color:#F00'>紅色字</p>") .append("<p style='text-align:right'>右對齊</p>"); helper.setText(sb.toString(), true); } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(message); }
注意:這裏建立的是MimeMessageHelper
,且在調用setText
時須要在第二個參數傳入true
,這樣纔會使用HTML格式發送郵件
經過velocity模板發送郵件:
<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下建一個templates包 該包下創建一個文件template.vm,內容以html格式隨便寫
<html>
<body>
<h3>你好, ${username}, 這是一封模板郵件!</h3>
</body>
</html>
測試結果: