使用 Amazon SES 和 Spring 启动发送电子邮件

Sending Emails with Amazon SES and Spring Boot

我有一个 SpringBoot 应用程序。具有此依赖项:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-aws</artifactId>
  <version>2.2.6.RELEASE</version>
</dependency>
<dependency>
  <groupId>io.awspring.cloud</groupId>
  <artifactId>spring-cloud-starter-aws-ses</artifactId>
  <version>2.3.3</version>
</dependency>

此配置文件:

@Configuration
public class MailConfig {

    @Bean
    public AmazonSimpleEmailService amazonSimpleEmailService() {

        return AmazonSimpleEmailServiceClientBuilder.standard()
                .withCredentials(new ProfileCredentialsProvider("ses-smtp-user.234221-1724219"))
                .withRegion(Regions.EU_WEST_2)
                .build();
    }

    @Bean
    public MailSender mailSender(
            AmazonSimpleEmailService amazonSimpleEmailService) {
        return new SimpleEmailServiceMailSender(amazonSimpleEmailService);
    }
}

@Service
public class NotificationService {
    
    private final MailSender mailSender;
    private final JavaMailSender javaMailSender;

    public NotificationService(MailSender mailSender, JavaMailSender javaMailSender) {
        this.mailSender = mailSender;
        this.javaMailSender = javaMailSender;
    }

    public void sendMailMessage(
            final SimpleMailMessage simpleMailMessage) {

        this.mailSender.send(simpleMailMessage);
    }

}

但是当我启动应用程序时。我有这个错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of constructor in com.dis.backend.service.NotificationService required a bean of type 'org.springframework.mail.javamail.JavaMailSender' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.mail.javamail.JavaMailSender' in your configuration.

根据错误消息,删除 NotificationService 构造函数中的 JavaMailSender 构造函数参数(假设您没有在 NotificationService 中使用它)。

如果您想在 NotificationService 中使用 JavaMailSender,您需要创建一个类型为 JavaMailSenderBean,它可以注入 NotificationService。对于 AWS-SES,您可以通过在配置中定义以下 bean 来实现。

@Bean
public JavaMailSender javaMailSender(AmazonSimpleEmailService amazonSimpleEmailService){
    return new SimpleEmailServiceJavaMailSender(amazonSimpleEmailService);
}