SpringBoot中郵件任務(wù)的使用
1. 引入依賴
在項(xiàng)目的 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 服務(wù),得到授權(quán)碼,如果直接配置郵箱賬號(hào)的明文密碼登錄,是無法登錄的。
3、編寫測(cè)試類測(cè)試發(fā)送郵件
測(cè)試類如下
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; //簡(jiǎn)單的郵件 @Test void contextLoads() { SimpleMailMessage message = new SimpleMailMessage(); message.setSubject("郵件主題--測(cè)試"); message.setText("這是郵件正文內(nèi)容,測(cè)試SpringBoot的郵件任務(wù)!"); message.setTo("2162759651@qq.com"); message.setFrom("2162759651@qq.com"); //發(fā)送 mailSender.send(message); } //復(fù)雜的郵件 @Test void contextLoadsMail() throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8"); //標(biāo)題及正文部分 helper.setSubject("復(fù)雜郵件-測(cè)試"); helper.setText("<p style='color:red'>這是郵件正文內(nèi)容,測(cè)試SpringBoot的郵件任務(wù)!</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); } }
測(cè)試結(jié)果
郵件能正常發(fā)送和接收
到此這篇關(guān)于SpringBoot中郵件任務(wù)的使用的文章就介紹到這了,更多相關(guān)SpringBoot郵件任務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中EasyExcel實(shí)現(xiàn)Excel文件的導(dǎo)入導(dǎo)出
這篇文章主要介紹了SpringBoot中EasyExcel實(shí)現(xiàn)Excel文件的導(dǎo)入導(dǎo)出,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Java并發(fā)編程之ReentrantLock實(shí)現(xiàn)原理及源碼剖析
ReentrantLock 是常用的鎖,相對(duì)于Synchronized ,lock鎖更人性化,閱讀性更強(qiáng),文中將會(huì)詳細(xì)的說明,請(qǐng)君往下閱讀2021-09-09SpringCloud Gateway跨域配置代碼實(shí)例
這篇文章主要介紹了SpringCloud Gateway跨域配置代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11java基礎(chǔ)之 Arrays.toString()方法詳解
這篇文章主要介紹了java基礎(chǔ)之 Arrays.toString()方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-02-02Java 多線程并發(fā)編程_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Java 多線程并發(fā)編程的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-05-05