SpringBoot中郵件任務的使用
更新時間:2023年10月18日 10:41:56 作者:yuhuofei2021
這篇文章主要介紹了SpringBoot中郵件任務的使用,SpringBoot?郵件任務是指使用SpringBoot框架來實現(xiàn)郵件發(fā)送和接收的功能,通過SpringBoot的自動配置和簡化的開發(fā)流程,我們可以輕松地集成郵件功能到我們的應用程序中,需要的朋友可以參考下
1. 引入依賴
在項目的 pom.xml 文件中,引入下面的依賴
<!--email依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 更改配置
在 application.properties 配置文件中,配置好郵箱的信息,例如下面的
#郵箱配置 spring.mail.username=2162759651@qq.com spring.mail.password=ejhvuqqibfrneafb spring.mail.host=smtp.qq.com spring.mail.properties.mail.smtp.ssl.enable=true

說明:這里用的是 qq 郵箱,需要開啟 POP3/SMTP 服務,得到授權碼,如果直接配置郵箱賬號的明文密碼登錄,是無法登錄的。

3、編寫測試類測試發(fā)送郵件
測試類如下
package com.yuhuofei;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootSwaggerApplicationTests {
@Autowired
private JavaMailSenderImpl mailSender;
//簡單的郵件
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("郵件主題--測試");
message.setText("這是郵件正文內容,測試SpringBoot的郵件任務!");
message.setTo("2162759651@qq.com");
message.setFrom("2162759651@qq.com");
//發(fā)送
mailSender.send(message);
}
//復雜的郵件
@Test
void contextLoadsMail() throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
//標題及正文部分
helper.setSubject("復雜郵件-測試");
helper.setText("<p style='color:red'>這是郵件正文內容,測試SpringBoot的郵件任務!</p>", true);
//附件
helper.addAttachment("1.png", new File("C:\\Users\\yuhuofei\\Desktop\\1.png"));
helper.addAttachment("2.png", new File("C:\\Users\\yuhuofei\\Desktop\\2.png"));
//發(fā)送
mailSender.send(message);
}
}
測試結果
郵件能正常發(fā)送和接收

到此這篇關于SpringBoot中郵件任務的使用的文章就介紹到這了,更多相關SpringBoot郵件任務內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot中EasyExcel實現(xiàn)Excel文件的導入導出
這篇文章主要介紹了SpringBoot中EasyExcel實現(xiàn)Excel文件的導入導出,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10
Java并發(fā)編程之ReentrantLock實現(xiàn)原理及源碼剖析
ReentrantLock 是常用的鎖,相對于Synchronized ,lock鎖更人性化,閱讀性更強,文中將會詳細的說明,請君往下閱讀2021-09-09
Java 多線程并發(fā)編程_動力節(jié)點Java學院整理
這篇文章主要介紹了Java 多線程并發(fā)編程的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-05-05

