之前做人事管理系统的时候涉及过邮件发送服务,业务场景就是公司面试通过之后会在人事管理系统中添加该员工信息,添加成功之后系统自动发送入职邮件。接入邮件服务比较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("gcs3048@163.com");
//发件人
helper.setFrom("304897438@qq.com");
//添加主题
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邮箱收件箱,证明邮件发送成功。