在Spring Cloud AWS中使用Java配置配置邮件发件人

时间:2019-05-29 13:22:03

标签: spring-boot spring-cloud-aws

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

documentation中,它提供XML以配置邮件发件人。有什么方法可以使用Java配置而不是XML?

2 个答案:

答案 0 :(得分: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. NotificationService
@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. application.yml
cloud:
  aws:
    credentials:
      accessKey: <YOUR_ACCESS_KEY>
      secretKey: <YOUR_SECRET_KEY>
    stack:
      auto: false

希望这会有所帮助。

答案 1 :(得分: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);
  }
}