Spring Boot傳送郵件
阿新 • • 發佈:2018-12-22
1.新增依賴
在pom.xml中新增下面的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、新增郵件配置引數
(1)yml配置,(注意:mail中host的配置字首需要是stmp),郵件可以是QQ,163,126等
spring:
# 外接jdbc和log配置檔案
profiles:
# 外接jdbc和log配置檔案
active: jdbc,log,redis
# 快取配置
cache:
type: ehcache
ehcache:
config: classpath:ehcache.xml
# thymeleaf配置
thymeleaf:
prefix: classpath:/templates/
check-template-location: true
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5
cache: false
# main配置
mail:
host: smtp.228.com.cn
username: [email protected]
password: xxxxxx
protocol: smtp
port: 25
(2)properties配置
spring.mail.default-encoding=utf-8
spring.mail.host=smtp.228.com.cn
[email protected]
spring.mail.password=xxxx
spring.mail.protocol=smtp
spring.mail.port=25
3、測試demo
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailException; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MailController { @Autowired JavaMailSender javaMailSender; @RequestMapping("/sendMail") public String sendMain(){ //建立郵件訊息 SimpleMailMessage simpleMailMessage=new SimpleMailMessage(); //訊息傳送者 simpleMailMessage.setFrom("
[email protected]"); //接受者 simpleMailMessage.setTo("[email protected]"); //訊息標題 simpleMailMessage.setSubject("測試啊"); //內容 simpleMailMessage.setText("哈嘍啊"); try { javaMailSender.send(simpleMailMessage); } catch (MailException ex) { System.err.println(ex.getMessage()); return "fail"; } return "success"; } }
4、測試
測試結果: