SpringBoot发送Gmail邮件
在Spring Boot中发送Gmail邮件需要以下步骤:
- 在Gmail设置中启用“对所有服务的访问权限”。
- 创建OAuth2.0客户端ID,用于生成客户端密钥和客户端秘密。
- 在Spring Boot项目中添加依赖和配置。
- 使用JavaMailSender发送邮件。
以下是一个简单的例子:
pom.xml依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
application.properties配置
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=your-gmail-username@gmail.com
spring.mail.password=your-client-secret
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
JavaMailSender配置
@Configuration
public class MailConfig {
@Bean
public JavaMailSender javaMailSender(MailProperties mailProperties) {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(mailProperties.getHost());
mailSender.setPort(mailProperties.getPort());
mailSender.setUsername(mailProperties.getUsername());
mailSender.setPassword(mailProperties.getPassword());
Properties properties = mailProperties.getProperties();
if (properties != null) {
mailSender.setJavaMailProperties(properties);
}
return mailSender;
}
}
发送邮件的服务
@Service
public class EmailService {
private final JavaMailSender mailSender;
@Autowired
public EmailService(JavaMailSender mailSender) {
this.mailSender = 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);
}
}
使用服务发送邮件
@RestController
public class EmailController {
private final EmailService emailService;
@Autowired
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@PostMapping("/sendEmail")
public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
emailService.sendEmail(to, subject, text);
return "Email sent successfully";
}
}
确保替换your-gmail-username@gmail.com
和your-client-secret
为你的Gmail用户名和客户端秘密。
发送邮件时,请确保你的应用已经授权并且客户端密钥和
评论已关闭