1. 程式人生 > >Springboot2.0.4呼叫qq郵箱傳送郵件

Springboot2.0.4呼叫qq郵箱傳送郵件

開場白:沒記錯的話,用不同框架開發一個發郵箱的功能,都會遇到多多少少的問題,這次也不能例外,否則就沒有意義了。 今天用springboot2.0.4開發發郵件功能,遇到了以下三個坑

  1. 專案中添加了該依賴,但是仍舊找不到

下面的物件,一直說該物件沒有被發現,後來發現是少了包

    @Autowired
	private JavaMailSender mailSender;

pom.xml中引入這兩個

<!--雖然我發現依賴裡面有了這個包,但是愣是不好使,非得讓我dependency一遍,被這個問題坑了半個小時-->
<dependency>           
		 <groupId>org.springframework</groupId>
		 <artifactId>spring-context-support</artifactId>  
		</dependency>

<!-- 呼叫發郵件的功能 -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

2 寫傳送的類。

package com.loy.spring;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class MailApplicationServiceTest {
	@Autowired
	private JavaMailSender mailSender;
	
	@Value("${spring.mail.username}")
	private String fromMail;
	@Test
	public void sendSimpleMail() throws Exception {

		SimpleMailMessage message = new SimpleMailMessage();

		message.setFrom(fromMail); // 必須要和上文配置的spring.mail.username內容相同

		message.setTo("
[email protected]
"); message.setSubject("主題:測試郵件"); message.setText("測試郵件內容"); System.out.println(fromMail); mailSender.send(message); }

注意上面的 @Value("${spring.mail.username}") 是從配置檔案中找的。 也就是需要再resources資料夾下增加 properties檔案,一般為 application.properties檔案,我是用qq傳送郵箱,內容如下:



#email
spring.mail.host=smtp.qq.com
[email protected]
spring.mail.password=uposqxqbtxzwighg spring.mail.properties.mail.smtp.ssl.trust=smtp.qq.com #SSL\u8BC1\u4E66Socket\u5DE5\u5382 spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory #\u4F7F\u7528SMTPS\u534F\u8BAE465\u7AEF\u53E3 spring.mail.properties.mail.smtp.socketFactory.port=465 spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true

spring.mail.password=uposqxqbtxzwighg 注意:這個密碼是qq開啟SMTP服務的授權碼,並不是你的真正的qq的密碼哦。按照這個配置貼上過去就行了哦。

  • 簡單來說 1 引入依賴 2 配置properties 3登陸qq郵箱獲取授權碼加入到properties中 3就是寫Test類,用JunitTest測試即可傳送郵件。

這就是Spring-boot呼叫郵箱發郵件的問題,對了,qq郵箱不能設定獨立密碼,否則郵件發不出去後,會報連線不上smtp.qq.com這個錯誤,切記。

====================================================== 結束語:不積跬步無以至千里,不積小流無以成江海

V:1861237242 歡迎java學習交流。