利用郵箱接口在springboot項目中發送郵件(以163郵箱爲例)

1.PC端登錄163郵箱,點擊設置按鈕,找到POP3/SMTP/IMAP,需要開啓它,如圖:

2.開啓授權密碼,其中會叫你設置授權密碼,設置完授權密碼後如圖:

3.添加maven依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

4.在springboot的配置文件中aplication.properties添加如下配置:

spring.mail.host=smtp.163.com   //郵箱服務器
spring.mail.username=***@163.com   //登錄郵箱的賬號
spring.mail.password=***           //這裏填的是你剛纔客戶端授權的密碼,而不是你登錄郵箱的密碼
spring.mail.default-encoding=UTF-8
spring.mail.protocol=smtps         //協議
spring.mail.port=465               //郵箱服務器端口
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

5.寫一個mailservice類,發送簡單純文本的郵件:

@Component
public class MyMailService  {
    @Autowired
    private MailSender mailSender;
    public void send() {
        // new 一個簡單郵件消息對象
        SimpleMailMessage message = new SimpleMailMessage();
        // 和配置文件中的的username相同,相當於發送方
        message.setFrom("***@163.com");
        // 收件人郵箱
        message.setTo("***@163.com");
        // 標題
        message.setSubject("主題:xxxx");
        // 正文
        message.setText("信息拉取失敗!");
        // 發送
        mailSender.send(message);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章