- 建立项目导入对应启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 测试邮箱(我这里用的qq邮箱)需要开启SMTP服务,得到对应的smtp码然后编写application.yaml配置
spring:
mail:
username: deeeelete@qq.com
password: [对应的smtp码]
host: smtp.qq.com
#qq邮箱需要特别开启
properties:
mail:
smtp:
ssl:
enable:
true
3. 在测试类中测试。
package com.yibu;
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;
@SpringBootTest
class YibuApplicationTests {
@Autowired
JavaMailSenderImpl javaMailSender;
@Test
void contextLoads() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setSubject("通知");
simpleMailMessage.setText("文本内容");
simpleMailMessage.setTo("deeeelete@qq.com");
simpleMailMessage.setFrom("deeeelete@qq.com");
javaMailSender.send(simpleMailMessage);
}
}
运行测试类:
- 或者我们希望发送带附件的邮件
@Test
void contextLoads2() throws MessagingException {
//一个复杂的邮件
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//组装
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
helper.setSubject("通知");
helper.setText("<h1 style='color:red'>文本内容</h1>",true);
//附件
helper.addAttachment("img.jpg",new File("D://字典/img.jpg"));
helper.setTo("deeeelete@qq.com");
helper.setFrom("deeeelete@qq.com");
javaMailSender.send(mimeMessage);
}