一个依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
获取授权码
配置和使用
#配置邮箱基本信息
spring:
mail:
host: smtp.qq.com #发送邮件服务器,请替换成自己的
properties.mail.smtp.port: 465 #端口号
username: 29xxxxx610@qq.com #发送邮件的邮箱地址,请替换成自己的
password: xxxxxnzlbybnfdfca #客户端授权码,不是邮箱密码,请替换成自己的
#邮件服务超时时间配置
properties.mail.smtp.connectiontimeout: 5000
properties.mail.smtp.timeout: 3000
properties.mail.smtp.writetimeout: 5000
#ssl开启配置
properties.mail.smtp.starttls.enable: true
properties.mail.smtp.starttls.required: true
properties.mail.smtp.ssl.enable: true
properties.mail.smtp.debug: true
default-encoding: utf-8 #邮件编码方式
package com.example.demo;
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.JavaMailSender;
@SpringBootTest
class DemoApplicationTests {
@Autowired(required = false)
private JavaMailSender javaMailSender;
@Test
void contextLoads() {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("296xxx4610@qq.com"); //发送方
message.setTo("286xxx897@qq.com"); //接收方
message.setSubject("恭喜你中奖了,一台洗衣机");
message.setText("请及时领取!");
javaMailSender.send(message);
}
@Test
void sendComplexMail() throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom("296xxx4610@qq.com");
helper.setTo("2725xxx473@qq.com");
helper.setSubject("王者官方");
String t1 = "<html><body><h3>国庆赠送皮肤,请注意及时查收!<h3>";
String t2 = "<img src='cid:aa' height='400px'";
String t3 = "</body></html>";
helper.setText(t1 + t2 + t3, true);
helper.addInline("aa", new File("C:\\Users\\CodeHaywire\\Desktop\\aa.png"));
// helper.addAttachment();
javaMailSender.send(mimeMessage);
}
}
over