Springboot整合mail
时间: 2024-03-03 22:28:26 浏览: 75
springboot整合mail邮箱
Spring Boot可以很方便地实现邮件发送功能,下面是整合Spring Boot和Java Mail的步骤:
1. 添加依赖:在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
2. 配置邮件发送信息:在`application.properties`文件中配置邮件发送的相关信息,例如:
```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.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
3. 创建邮件发送服务:创建一个邮件发送服务类,例如`MailService`,并注入`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 MailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
javaMailSender.send(message);
}
}
```
4. 使用邮件发送服务:在需要发送邮件的地方,注入`MailService`并调用`sendEmail`方法来发送邮件:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
@Autowired
private MailService mailService;
@RequestMapping("/sendEmail")
public String sendEmail() {
String to = "recipient@example.com";
String subject = "Test Email";
String content = "This is a test email.";
mailService.sendEmail(to, subject, content);
return "Email sent successfully";
}
}
```
这样,当访问`/sendEmail`接口时,就会发送一封测试邮件到指定的收件人邮箱。
以上就是Spring Boot整合Java Mail实现邮件发送的基本步骤。你可以根据自己的需求进一步定制邮件内容、添加附件等功能。
阅读全文