首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在SpringBoot中使用JavaMailSender

在Spring Boot中使用JavaMailSender发送电子邮件是一个常见的任务。以下是如何配置和使用JavaMailSender的步骤:

1. 添加依赖

首先,在你的pom.xml文件中添加Spring Boot的邮件支持依赖:

代码语言:javascript
复制
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

2. 配置邮件属性

application.propertiesapplication.yml文件中配置邮件发送相关的属性:

application.properties 示例:

代码语言:javascript
复制
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

application.yml 示例:

代码语言:javascript
复制
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.comyour-email@example.comyour-email-password为你的SMTP服务器信息和登录凭证。

3. 注入JavaMailSender

在你的服务类中注入JavaMailSender接口:

代码语言:javascript
复制
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);
    }
}

4. 发送邮件

现在你可以使用EmailService来发送邮件了:

代码语言:javascript
复制
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端点时,它会触发邮件发送过程。

注意事项

  • 确保你的SMTP服务器配置正确,并且允许从你的应用程序发送邮件。
  • 如果使用Gmail等服务,可能需要生成一个专用的应用密码,而不是使用你的常规账户密码。
  • 考虑使用环境变量或配置服务器来管理敏感信息,如邮箱密码。
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券