1、添加发送邮件需要的maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
</parent>
<groupId>pers.th</groupId>
<artifactId>email</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、添加邮箱配置参数
spring:
mail:
host: smtp.qq.com
port: 25
username: xxx@qq.com
password: xxx
3.编写测试类
package pers.th.email;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
@SpringBootTest
class EmailApplicationTests {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Test
public void sendEmail(){
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo("xxx@qq.com");
message.setSubject("hello world!");
message.setText("hello world!");
mailSender.send(message);
System.out.println("发送成功");
}catch (Exception e){
e.printStackTrace();
}
}
@Test
public void contextLoads() {
System.out.println(1);
}
}