SpringBoot+mail 轻松实现各类邮件自动推送
在Spring Boot中实现邮件自动推送功能,你可以使用spring-boot-starter-mail
库。以下是一个简单的例子,展示了如何配置邮件服务器并发送一封简单邮件。
- 添加依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
- 在
application.properties
或application.yml
中配置你的邮件服务器:
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your_username
spring.mail.password=your_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
- 创建一个MailService来发送邮件:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
@Service
public class MailService {
private final JavaMailSender mailSender;
@Autowired
public MailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendSimpleMail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
}
- 在你的应用中使用MailService来发送邮件:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MailController {
private final MailService mailService;
@Autowired
public MailController(MailService mailService) {
this.mailService = mailService;
}
@GetMapping("/sendMail")
public String sendMail() {
mailService.sendSimpleMail("recipient@example.com", "Test Subject", "This is the email content");
return "Mail sent!";
}
}
确保你的应用配置了正确的邮件服务器信息,并且sendMail
端点可以被调用来发送邮件。这个例子展示了如何发送文本邮件,如果你需要发送HTML邮件或者附件,你可以使用MimeMessageHelper
来扩展SimpleMailMessage
。
评论已关闭