SpringBoot 发送邮件
时间: 2024-09-18 14:06:55 浏览: 98
Spring Boot发送邮件通常通过JavaMail API实现,Spring Boot提供了一个方便的集成方式,无需额外配置SMTP服务器。以下是使用Spring Boot发送邮件的基本步骤:
1. 添加依赖:在`pom.xml`文件中添加Spring Boot Actuator和JavaMail的相关依赖,例如:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
2. 配置邮箱服务:在application.properties或application.yml文件中设置SMTP服务器的信息,如主机名、端口、用户名、密码等:
```properties
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your-email@example.com
spring.mail.password=your-password
spring.mail.protocol=smtp
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
3. 创建邮件消息:创建一个Java类,继承`AbstractMessageConverter`或使用`SimpleMailMessage`来构建邮件内容:
```java
import org.springframework.mail.SimpleMailMessage;
SimpleMailMessage message = new SimpleMailMessage();
message.setTo("recipient@example.com");
message.setFrom("sender@example.com");
message.setSubject("Hello from Spring Boot");
message.setText("This is a test email.");
```
4. 使用Java配置或注解:在Spring Boot应用中,你可以使用Java配置类配置一个`JavaMailSender`实例,然后在需要的地方发送邮件:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(SimpleMailMessage message) {
javaMailSender.send(message);
}
```
或者使用`@Autowired`自动注入并在方法上使用`@SendMail`注解:
```java
@RestController
public class EmailController {
@Autowired
private JavaMailSender javaMailSender;
@PostMapping("/send-email")
@SendMail
public ResponseEntity<String> sendMessage(SimpleMailMessage message) {
// ...处理并返回响应
}
}
```
阅读全文