导入依赖
bash
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2.在properties配置邮箱
bash
# 发件人QQ号
spring.mail.username=2508575653@qq.com
# QQ邮箱授权码
spring.mail.password=xxxxxxxxxxxxxxx
# 主机
spring.mail.host=smtp.qq.com
# qq邮箱需要开启安全连接
spring.mail.properties.mail.stmp.ssl.enable=true
3.获取QQ邮箱授权码
打开网页版的QQ邮箱,登录邮箱,进入设置-》帐户
然后,在"帐户"设置中,找到服务设置项,进行设置,如下:
开启POP3/SMTP服务器,验证密保
用正确的手机好发送正确的验证内容到指定的号码,成功获取授权码
测试代码
java
package com.peng;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@SpringBootTest
class SpringbootSecurityApplicationTests {
@Autowired
private JavaMailSenderImpl javaMailSender;
@Test
void contextLoads() {
//简单邮件
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("测试");//主题
message.setText("邮箱内容");
、//接受者邮箱(任何邮箱都可以)
message.setTo("2508575653@qq.com");
//发送者邮箱
message.setFrom("2508575653@qq.com");
javaMailSender.send(message);
}
@Test
void test() throws MessagingException {
//复杂邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);//组装,开启之后可以添加附件
helper.setSubject("ok");//主题
helper.setText("内容");
helper.addAttachment("按什么名称发送.后缀",new File("文件路径"));
helper.setTo("收件人");
helper.setFrom("发件人");
javaMailSender.send(mimeMessage);
}
}