在 Spring 里实现邮件发送支持,可借助 Spring 的 JavaMailSender
接口达成。以下为详细步骤和示例代码:
1. 添加依赖
若使用 Maven 项目,要在 pom.xml
里添加如下依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
2. 配置邮件服务
在 application.properties
或者 application.yml
中配置邮件服务相关信息,以 application.properties
为例:
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your-email@example.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
3. 创建邮件发送服务类
创建一个服务类来处理邮件发送的逻辑:
MailService.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 MailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendSimpleEmail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
4. 使用邮件发送服务
在控制器或者服务类中注入 MailService
并调用其方法发送邮件:
MailController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MailController {
@Autowired
private MailService mailService;
@GetMapping("/send-mail")
public String sendMail(@RequestParam String to, @RequestParam String subject, @RequestParam String text) {
try {
mailService.sendSimpleEmail(to, subject, text);
return "Email sent successfully";
} catch (Exception e) {
return "Error sending email: " + e.getMessage();
}
}
}
代码解释
- 依赖添加:
spring-boot-starter-mail
依赖包含了 Spring 对邮件发送的支持。 - 配置邮件服务:对邮件服务器的主机、端口、用户名、密码等信息进行配置。
- 邮件发送服务类:
MailService
类借助JavaMailSender
发送简单的文本邮件。 - 控制器类:
MailController
类提供了一个 RESTful 接口/send-mail
,用于调用邮件发送服务。
按照以上步骤,你就能在 Spring 项目中实现邮件发送的支持了。