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

  • 2020 年 1 月 14 日
  • 筆記

大家好,我是潤森。期末化學已掛,誰來燒紙,掛得又有動力學習了?

Python發郵件

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

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

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

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

Java發郵件

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

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

mavenjavax.mail

創建maven工程,就搞定

<!-- https://mvnrepository.com/artifact/cn.howardliu/gear-email -->  <dependency>      <groupId>cn.howardliu</groupId>      <artifactId>gear-email</artifactId>      <version>1.0.1-RELEASE</version>  </dependency>

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

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

使用Springboot發郵件

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

開通SMTP服務

需要拿到授權碼

創建SpringBoot項目

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

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

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

application.properties項目配置

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

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

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);      }  }  

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

成功接收

上傳文件

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

文件

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

@Test  public void test02() throws Exception {      //1、創建一個複雜的消息郵件      MimeMessage mimeMessage = mailSender.createMimeMessage();      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);        //郵件設置      helper.setSubject("通知-潤森交下書最近的情況");      helper.setText("<b style='color:red'>其實我啥都沒寫</b>", true);        helper.setTo("[email protected] ");      helper.setFrom("[email protected]");          //上傳文件      helper.addAttachment("第二章.md", new File("C:\Users\YIUYE\Desktop\數據之道\Python數據分析\第二章.md"));          mailSender.send(mimeMessage);    }

成功接受

結語

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

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