springboot 实现邮件发送
时间: 2024-04-24 16:20:19 浏览: 97
Spring Boot是一个用于创建独立的、基于Spring的应用程序的框架。它提供了许多开箱即用的功能,包括邮件发送。下面是使用Spring Boot实现邮件发送的步骤:
1. 添加依赖:在项目的pom.xml文件中添加Spring Boot的邮件依赖,例如:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
2. 配置邮件信息:在application.properties或application.yml文件中配置邮件服务器的相关信息,例如:
```properties
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your-email@example.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
3. 创建邮件服务类:创建一个邮件服务类,用于发送邮件。可以使用JavaMailSender来发送邮件,例如:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
public void sendEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}
```
4. 调用邮件服务类:在需要发送邮件的地方调用邮件服务类的sendEmail方法,例如:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/sendEmail")
public String sendEmail() {
emailService.sendEmail("recipient@example.com", "Test Email", "This is a test email.");
return "Email sent successfully.";
}
}
```
以上就是使用Spring Boot实现邮件发送的基本步骤。
阅读全文