使用spring-boot-starter-mail发送邮件
时间: 2024-11-15 16:14:38 浏览: 6
Spring Boot Starter Mail是一个轻量级的启动器,它包含了发送电子邮件所需的基本依赖,使得在Spring Boot应用中集成邮箱功能变得更加简单。要使用这个组件,首先你需要添加`spring-boot-starter-mail`到你的项目的`pom.xml`或者`build.gradle`文件中。
以下是基本步骤:
1. 添加依赖:在Maven中,添加到`<dependencies>`标签内:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
在Gradle中,添加到`dependencies`块中:
```groovy
implementation 'org.springframework.boot:spring-boot-starter-mail'
```
2. 配置邮件服务器:在`application.properties`或`application.yml`中设置发件人的邮箱地址、SMTP服务器信息,例如:
```properties
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=myemail@example.com
spring.mail.password=mypassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
3. 创建Java配置类,如`MailSenderConfiguration`,并注入`JavaMailSender`:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
@Configuration
public class MailSenderConfig {
@Autowired
private JavaMailSender javaMailSender;
// 省略其他配置方法...
}
```
4. 实现发送邮件的Service或者Repository,调用`javaMailSender`实例的方法,比如:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
@Autowired
private JavaMailSender mailSender;
public void sendEmail(SimpleMailMessage message) {
mailSender.send(message);
}
```
5. 使用`SimpleMailMessage`构造函数构建邮件内容:
```java
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo("recipient@example.com");
mailMessage.setSubject("测试邮件");
mailMessage.setText("这是一封测试邮件的内容.");
sendEmail(mailMessage);
```
阅读全文