相信使用過Spring的衆多開發者都知道Spring提供了非常好用的JavaMailSender
接口實現郵件發送。在Spring Boot的Starter模塊中也爲此提供了自動化配置。下面通過實例看看如何在Spring Boot中使用JavaMailSender
發送郵件。
快速入門
在Spring Boot的工程中的pom.xml
中引入spring-boot-starter-mail
依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
如其他自動化配置模塊一樣,在完成了依賴引入之後,只需要在application.properties
中配置相應的屬性內容。
下面我們以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
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest//新版本
//@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("你好");
mailSender.send(message);
}
}