在Spring Boot中使用JavaMailSender发送电子邮件是一个常见的任务。以下是如何配置和使用JavaMailSender的步骤:
首先,在你的pom.xml
文件中添加Spring Boot的邮件支持依赖:
<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-email@example.com
spring.mail.password=your-email-password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring:
mail:
host: smtp.example.com
port: 587
username: your-email@example.com
password: your-email-password
properties:
mail:
smtp:
auth: true
starttls:
enable: true
请确保替换smtp.example.com
、your-email@example.com
和your-email-password
为你的SMTP服务器信息和登录凭证。
在你的服务类中注入JavaMailSender
接口:
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 final JavaMailSender javaMailSender;
@Autowired
public EmailService(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void sendSimpleMessage(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(text);
javaMailSender.send(message);
}
}
现在你可以使用EmailService
来发送邮件了:
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 final EmailService emailService;
@Autowired
public EmailController(EmailService emailService) {
this.emailService = emailService;
}
@GetMapping("/send-email")
public String sendEmail() {
emailService.sendSimpleMessage("recipient@example.com", "Hello", "This is a test email.");
return "Email sent!";
}
}
当你访问/send-email
端点时,它会触发邮件发送过程。
领取专属 10元无门槛券
手把手带您无忧上云