相信使用過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=用戶名
spring.mail.password=密碼
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
通過單元測試來實(shí)現(xià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("[email protected]");
message.setTo("[email protected]");
message.setSubject("主題:簡單郵件");
message.setText("測試郵件內(nèi)容");
mailSender.send(message);
}
}
到這里,一個(gè)簡單的郵件發(fā)送就完成了,運(yùn)行一下該單元測試,看看效果如何?
由于Spring Boot的starter模塊提供了自動(dòng)化配置,所以在引入了spring-boot-starter-mail依賴之后,會(huì)根據(jù)配置文件中的內(nèi)容去創(chuàng)建JavaMailSender實(shí)例,因此我們可以直接在需要使用的地方直接@Autowired來引入郵件發(fā)送對(duì)象。
#代碼示例
本文的相關(guān)例子可以查看下面?zhèn)}庫中的chapter4-5-1
目錄:
- Github:https://github.com/dyc87112/SpringBoot-Learningopen in new window
- Gitee:https://gitee.com/didispace/SpringBoot-Learning