Springboot 集成Gmail
时间: 2024-04-04 17:26:21 浏览: 160
Spring Boot可以通过配置SMTP服务器来实现与Gmail的集成。以下是集成Gmail的步骤:
1. 在`application.properties`文件中添加以下配置:
```properties
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-email@gmail.com
spring.mail.password=your-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
请将`your-email@gmail.com`和`your-password`替换为您自己的Gmail帐户的电子邮件地址和密码。
2. 在您的Spring Boot应用程序中创建一个邮件服务类,例如`EmailService`,并注入`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 javaMailSender;
public void sendEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
```
3. 在您的应用程序中使用`EmailService`发送电子邮件:
```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("/send-email")
public String sendEmail() {
emailService.sendEmail("recipient@example.com", "Test Email", "This is a test email.");
return "Email sent successfully.";
}
}
```
以上步骤将使您的Spring Boot应用程序能够通过Gmail SMTP服务器发送电子邮件。
阅读全文