温馨提示×

SpringBoot中怎么实现邮件发送功能

小亿
83
2024-03-07 12:59:27
栏目: 编程语言

在SpringBoot中实现邮件发送功能可以使用Spring的邮件发送模块spring-boot-starter-mail,并在application.properties文件中配置邮件发送的相关信息。

首先,在pom.xml文件中引入spring-boot-starter-mail依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

然后在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

接下来,在Java代码中编写邮件发送的服务类,示例代码如下:

@Service
public class EmailService {

    @Autowired
    private JavaMailSender javaMailSender;

    public void sendEmail(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);

        javaMailSender.send(message);
    }
}

最后,在需要发送邮件的地方调用EmailService中的sendEmail方法即可发送邮件。例如:

@Autowired
private EmailService emailService;

emailService.sendEmail("recipient@example.com", "Test Email", "This is a test email from SpringBoot.");

这样就可以在SpringBoot中实现邮件发送功能了。

0