springboot集成email qq邮箱
时间: 2023-09-17 11:11:29 浏览: 94
你可以使用Spring Boot集成JavaMail来发送电子邮件,包括QQ邮箱。首先,你需要在Spring Boot项目的pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
```
然后,在你的application.properties(或application.yml)文件中配置QQ邮箱的SMTP服务器信息:
```properties
spring.mail.host=smtp.qq.com
spring.mail.port=587
spring.mail.username=your-email@qq.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
```
请确保将 "your-email@qq.com"和"your-email-password" 替换为你自己的QQ邮箱地址和密码。
接下来,你可以创建一个包含邮件发送逻辑的Service类。下面是一个简单的示例:
```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 {
private JavaMailSender javaMailSender;
@Autowired
public EmailService(JavaMailSender javaMailSender) {
this.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);
}
}
```
在你的Controller或其他地方使用这个Service类来发送邮件。例如:
```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 {
private EmailService emailService;
@Autowired
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@GetMapping("/sendEmail")
public String sendEmail() {
String to = "recipient-email@example.com";
String subject = "Test Email";
String text = "This is a test email from Spring Boot.";
emailService.sendEmail(to, subject, text);
return "Email sent successfully!";
}
}
```
记得将 "recipient-email@example.com" 替换为你要发送邮件的收件人地址。
这样,当你访问 "/sendEmail" 路径时,就会触发邮件发送。确保你的应用程序能够连接到互联网以及QQ邮箱的SMTP服务器。
阅读全文