0

I want to send emails using Amazon SES, Spring Cloud AWS and Spring Boot 2.1.5.

In the documentation, it provides XML to configure the mail sender. Is there any way to use Java config instead of XML?

Swordfish
  • 1,127
  • 24
  • 46

2 Answers2

0

Got it to work, here's what I did.

  1. Build dependencies
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.cloud:spring-cloud-starter-aws'
    implementation 'com.amazonaws:aws-java-sdk-ses'
  1. Config 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

Hope this helps.

Swordfish
  • 1,127
  • 24
  • 46
0

I changed the config file to this and it works fine.I hope it helps

@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);
  }
}
Milapappy
  • 1
  • 1
  • 1