史上最簡單易懂的JAVA發送郵件與報錯處理
目錄
- 史上最簡單易懂的JAVA發送郵件與報錯處理
-
- 一、導入依賴
- 二、配置郵件屬性
- 三、寫測試用例
- 四、幾種遇到的情況與解決辦法
-
-
-
- 1.535錯誤
- 2.加載逾時
-
-
小編不說廢話了直接開整
一、導入依賴
首先導入對應的依賴
代碼:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
二、配置郵件屬性
這也是簡單又容易犯錯的地方
代碼:
spring.mail.default-encoding=UTF-8
#标明使用哪種郵箱
spring.mail.host=smtp.qq.com
#發送者的郵箱賬号
spring.mail.username=*********
#發送者的郵箱密碼(QQ是授權碼)
spring.mail.password=*********
#端口(預設是25端口)
spring.mail.port=465
#協定
spring.mail.protocol=smtp
#啟用465等端口使用如下代碼
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
#本次服務的端口号
server.port=8081
三、寫測試用例
沒什麼好講的了直接抄過去
代碼:
@RestController
public class MailController {
@Autowired
JavaMailSender jms;
@GetMapping("/send")
public String send(){
//建立郵件消息
SimpleMailMessage mainMessage = new SimpleMailMessage();
//發送者
mainMessage.setFrom("**********@qq.com");
//接收者
mainMessage.setTo("**********@qq.com");
//發送的标題
mainMessage.setSubject("嗨喽");
//發送的内容
mainMessage.setText("hello world");
jms.send(mainMessage);
return "發送成功!";
}
}
結果:
四、幾種遇到的情況與解決辦法
1.535錯誤
授權碼或賬号不對造成的
2.加載逾時
使用465端口需要配置SSL上面代碼已給出或者可能你的郵箱沒有開通smtp這項服務