SpringBoot发送邮件
1 获取QQ的SMTP授权码
2 导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
3 application.yml加入配置
mail:
username: 1198247262@qq.com
# 这个密码就是smtp授权码
password: sobaxyrlqmxcgiib
# host如果是qq就写qq,163就写163
host: smtp.qq.com
# 开启加密验证(这个只有qq有)
properties:
mail:
smtp:
ssl:
enable: true
4编写测试类
package com.tan.sendMail;
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;
/**
* @author tlj
* @date 2021/11/16 15:34:18
*/
@SpringBootTest
public class SendMailTest {
@Autowired
JavaMailSenderImpl javaMailSender;
//简单邮件
@Test
public void sendMail() {
SimpleMailMessage mailMessage = new SimpleMailMessage();
//标题
mailMessage.setSubject("测试发邮件");
mailMessage.setText("邮件正文");
//发送方
mailMessage.setFrom("119847262@qq.com");
//接收方
mailMessage.setTo("85267635@qq.com");
javaMailSender.send(mailMessage);
}
//复杂邮件
@Test
public void sendMail2() {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//标题
helper.setSubject("这是title");
// true 表示解析支持html
helper.setText("<p style='color:red'>邮件正文内容!</p>", true);
// 附件
helper.addAttachment("小姐姐.jpg", new File("C:\\Users\\Administrator\\Pictures\\getImg.jpg"));
// 发送方
helper.setFrom("1198247262@qq.com");
//接收方
helper.setTo("857267635@qq.com");
javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}