从零搭建开发脚手架 Spring Boot实现邮件功能
以下是一个使用Spring Boot实现发送邮件功能的简单示例:
- 首先,在
pom.xml
中添加Spring Boot邮件发送所需依赖:
<dependencies>
<!-- Spring Boot Starter for Mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Spring Boot Starter for Web (如果需要Web接口) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
- 在
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
- 创建一个邮件服务类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
private final JavaMailSender mailSender;
@Autowired
public EmailService(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
- 创建一个REST控制器来提供发送邮件的接口:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class EmailController {
private final EmailService emailService;
@Autowired
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@PostMapping("/send-email")
public String sendEmail(@RequestParam String to, @RequestParam String subject, @RequestParam String content) {
emailService.sendSimpleMail(to, subject, content);
return "Email sent successfully!";
}
}
- 最后,创建Spring Boot应用类:
import org.springframework.boot.SpringAp
评论已关闭