之前做人事管理系統的時候涉及過郵件發送服務,業務場景就是公司面試通過之後會在人事管理系統中添加該員工信息,添加成功之後系統自動發送入職郵件。接入郵件服務比較easy,這裏記錄一下搭建簡單的郵件服務。
開啓POP3/SMTP服務
首先,在項目中加入郵件服務需要開啓POP3/SMTP服務
,以QQ郵箱爲例:
登錄QQ郵—–》設置—–》賬戶—–》開啓POP3/SMTP服務
開啓服務的時候會讓我們發送一條短信進行驗證,驗證成功之後會給一個授權碼:
將該授權碼複製下來,後面的配置文件中需要使用到該授權碼:
引入mail依賴
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
mail相關配置
server:
port: 8086
spring:
mail:
default-encoding: utf-8
username: 304897438@qq.com
password: 這裏填寫開啓POP3/SMTP服務的時候給的授權碼
host: smtp.qq.com
#開啓加密驗證
properties:
mail:
smtp:
ssl:
enable: true
相關測試代碼
package org.magic.mail;
import java.io.File;
import javax.mail.Address;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
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.javamail.MimeMessageHelper;
@SpringBootTest
class MailApplicationTests {
@Autowired
private JavaMailSenderImpl mailSender;
@Test
void contextLoads() throws MessagingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//收件人
helper.setTo("[email protected]");
//發件人
helper.setFrom("[email protected]");
//添加主題
helper.setSubject("郵件的主題");
//添加內容
helper.setText("今天微風不燥,睡覺正好");
//添加附件
//1.附件名稱
String attachmentName = "123.jpg";
//2.附件路徑
File file = new File("D://123.jpg");
helper.addAttachment(attachmentName, file);
//發送
mailSender.send(mimeMessage);
}
}
通過以上幾行代碼就可以發送自己的郵件了。下面是163郵箱收件箱,證明郵件發送成功。