springboot邮件发送接口开发
时间: 2024-04-09 20:26:30 浏览: 134
springboot接口开发
Spring Boot提供了简单且强大的邮件发送接口开发功能。你可以使用Spring Boot的JavaMailSender接口来发送邮件。下面是一个简单的示例代码:
1. 首先,确保在你的项目中添加了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=your-smtp-server
spring.mail.port=your-smtp-port
spring.mail.username=your-username
spring.mail.password=your-password
```
3. 创建一个邮件发送服务类,例如:
```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() {
String to = "recipient@example.com";
String subject = "Test Email";
String text = "This is a test email.";
emailService.sendEmail(to, subject, text);
return "Email sent successfully.";
}
}
```
这样,当你访问`/sendEmail`接口时,就会发送一封测试邮件到指定的收件人邮箱。
阅读全文