SpringBoot中郵件任務(wù)的使用
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 服務(wù),得到授權(quán)碼,如果直接配置郵箱賬號的明文密碼登錄,是無法登錄的。
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("這是郵件正文內(nèi)容,測試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ù)雜郵件-測試"); helper.setText("<p style='color:red'>這是郵件正文內(nèi)容,測試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); } }
測試結(jié)果
郵件能正常發(fā)送和接收
到此這篇關(guān)于SpringBoot中郵件任務(wù)的使用的文章就介紹到這了,更多相關(guān)SpringBoot郵件任務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中EasyExcel實現(xiàn)Excel文件的導(dǎo)入導(dǎo)出
這篇文章主要介紹了SpringBoot中EasyExcel實現(xiàn)Excel文件的導(dǎo)入導(dǎo)出,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10Java并發(fā)編程之ReentrantLock實現(xiàn)原理及源碼剖析
ReentrantLock 是常用的鎖,相對于Synchronized ,lock鎖更人性化,閱讀性更強,文中將會詳細的說明,請君往下閱讀2021-09-09java基礎(chǔ)之 Arrays.toString()方法詳解
這篇文章主要介紹了java基礎(chǔ)之 Arrays.toString()方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02Java 多線程并發(fā)編程_動力節(jié)點Java學(xué)院整理
這篇文章主要介紹了Java 多線程并發(fā)編程的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-05-05