Springboot發郵件,你還不會來打我

@Author:By Runsen

Python發郵件

Python發郵件是個小兒科,只需要使用 smtplib和email

smtplib是用來發送郵件用的,email是用來構建郵件內容的。

具體博客鏈接:https://maoli.blog.csdn.net/article/details/89857715

小兒科的東西就不一一論述了

Java發郵件

菜鳥教程迎接有具體教程,

https://www.runoob.com/java/java-sending-email.html

去maven搜javax.mail

Springboot發郵件,你還不會來打我

創建maven工程,就搞定

<code>
<dependency>
<groupid>cn.howardliu/<groupid>
<artifactid>gear-email/<artifactid>
<version>1.0.1-RELEASE/<version>
/<dependency>/<code>

搜了下Email竟然高達600多jar包,可見Java得強大

Springboot發郵件,你還不會來打我

其中使用Springboot發郵件,廣泛運用

使用Springboot發郵件

Spring 提供了JavaMailSender 接口幫我們來實現郵件的發送。在SpringBoot 更是提供了郵件的發送的 starter 依賴來簡化郵件發送代碼的開發 。

開通SMTP服務

Springboot發郵件,你還不會來打我

創建SpringBoot項目

創建SpringBoot項目,只需要引用Web模塊即可

在項目的pom.xml文件中引用spring-boot-starter-mail

<code><dependency>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-starter-mail/<artifactid>
/<dependency>/<code>

application.properties項目配置

<code>[email protected]
spring.mail.password=授權碼
spring.mail.host=smtp.qq.com
spring.mail.properties.mail.smtp.ssl.enable=true/<code>
TaskApplicationTests.java測試類

只需要wiredJavaMailSenderImpl進行@Auto標註就ok

<code>import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.SimpleMailMessage;

@SpringBootTest
class TaskApplicationTests {

@Autowired
JavaMailSenderImpl mailSender;

@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("通知-潤森有空寫書");
simpleMailMessage.setText("今晚7:30寫下博客");
simpleMailMessage.setTo("[email protected] ");
simpleMailMessage.setFrom("[email protected]");
mailSender.send(simpleMailMessage);
}
}
/<code>

運行測試,這樣我的QQ郵箱[email protected]發送郵件到我的126郵箱[email protected]

Springboot發郵件,你還不會來打我

成功接收

上傳文件

發個消息有什麼意思呢?我萬一要發個文件怎麼辦?

Springboot發郵件,你還不會來打我

文件

其實創建一個複雜的消息郵件mailSender,mailSender是Java內置的jar包,通過addAttachment方法簡單解決

<code>@Test
public void test02() throws Exception {
//1、創建一個複雜的消息郵件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

//郵件設置
helper.setSubject("通知-潤森交下書最近的情況");
helper.setText("其實我啥都沒寫", true);

helper.setTo("[email protected] ");
helper.setFrom("[email protected]");


//上傳文件
helper.addAttachment("第二章.md", new File("C:\\\\Users\\\\YIUYE\\\\Desktop\\\\數據之道\\\\Python數據分析\\\\第二章.md"));


mailSender.send(mimeMessage);

}/<code>

成功接受

Springboot發郵件,你還不會來打我

結語

SpringBoot中集成郵件服務記錄,小白成長中,望不吝賜教

再自我介紹一下吧。我叫潤森,是一個的學習者,分享自己的所學所得。


分享到:


相關文章: