目錄
獲取QQ 授權碼
SpringBoot構建
依賴
Yaml配置
服務編寫
測試
獲取QQ 授權碼
https://mail.qq.com/
接著后就會有對應的密鑰了
SpringBoot構建
依賴
這里的建議是 2.0系列的Springboot版本用低一點的郵件依賴
<!-- 電子郵件 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId><version>2.7.18</version>
</dependency>
Yaml配置
spring:mail:default-encoding: UTF-8host: smtp.qq.comport: 587username: 你的郵件password: 剛剛QQ生成的密鑰properties:mail:smtp:starttls:enable: trueauth: truesocketFactory:class: javax.net.ssl.SSLSocketFactorydebug: true
服務編寫
為了方便直接寫在 控制層 了
package com.takem.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class EmailController {@Autowiredprivate JavaMailSender mailSender;@GetMapping("/email")public String sendSimpleMessage() {SimpleMailMessage mailMessage = new SimpleMailMessage();mailMessage.setFrom("自己的郵箱");mailMessage.setTo("別人的郵箱");mailMessage.setText("這是內容");mailMessage.setSubject("這是郵件標題");mailSender.send(mailMessage);return "====完成發送!====";}
}
測試
以自己發給自己為例