0

我想使用 Amazon SES、Spring Cloud AWS 和 Spring Boot 2.1.5 发送电子邮件。

文档中,它提供了 XML 来配置邮件发送者。有什么方法可以使用 Java 配置而不是 XML?

4

2 回答 2

0

让它工作,这就是我所做的。

  1. 构建依赖项
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.cloud:spring-cloud-starter-aws'
    implementation 'com.amazonaws:aws-java-sdk-ses'
  1. 配置 bean
@Configuration
public class AwsConfig {

    @Bean
    public AmazonSimpleEmailService amazonSimpleEmailService(AWSCredentialsProvider credentialsProvider) {
         return AmazonSimpleEmailServiceClientBuilder.standard()
            .withCredentials(credentialsProvider)
            .withRegion(Regions.EU_WEST_1).build();
    }

    @Bean
    public MailSender mailSender(AmazonSimpleEmailService ses) {
        return new SimpleEmailServiceMailSender(ses);
    }    
}
  1. 通知服务
@Service
public class NotificationService {

    @Autowired
    private MailSender mailSender;

    public void sendMailMessage() {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("sender@mail.com");
        simpleMailMessage.setTo("to@mail.com");
        simpleMailMessage.setSubject("test subject");
        simpleMailMessage.setText("test text");
        this.mailSender.send(simpleMailMessage);
    }
}
  1. 应用程序.yml
cloud:
  aws:
    credentials:
      accessKey: <YOUR_ACCESS_KEY>
      secretKey: <YOUR_SECRET_KEY>
    stack:
      auto: false

希望这可以帮助。

于 2019-05-30T09:28:13.670 回答
0

我将配置文件更改为此,它工作正常。我希望它有帮助

@Configuration
public class AwsMailConfig {

  @Bean
  public AmazonSimpleEmailService amazonSimpleEmailService() {

    BasicAWSCredentials basicAWSCredentials =
        new BasicAWSCredentials(
            <AWS_ACCESS_KEY>,<AWS_SECRET_KEY>);

    return AmazonSimpleEmailServiceClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
        .withRegion(Regions.EU_WEST_1)
        .build();
  }

  @Bean
  public JavaMailSender javaMailSender(AmazonSimpleEmailService amazonSimpleEmailService) {
    return new SimpleEmailServiceJavaMailSender(amazonSimpleEmailService);
  }
}
于 2019-12-05T11:04:04.113 回答