Home > front end >  Using Amazon SES in one environment and gmail SMTP in the other environment in spring boot
Using Amazon SES in one environment and gmail SMTP in the other environment in spring boot

Time:03-08

I have a situation where I would like to use Gmail SMTP in my environment 1 and Amazon SES in environment 2 to send emails. I know how to achieve each of these individually but can't get it to work for both in such a way that I don't have to do special setups for different environments.

The problem I am struggling with is that for Gmail SMTP, the properties are defined in the application.properties file and I am using auto-configuration like below

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=myEmail
spring.mail.password=myPassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

But for SES, I am defining the configuration bean, like below-

@Configuration
public class EmailConfig {

  @Bean
  public AmazonSimpleEmailService amazonSimpleEmailService() {

    return AmazonSimpleEmailServiceClientBuilder.standard()
        .build();
  }

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

I have tried:

  1. Finding a way to define SES email configurations in my env2's application.properties but couldn't make it work because this configuration uses IAM role to send emails. The configuration class you see above is all I have and all that is required to send emails. (no secret key, access key).
  2. Finding a way to define my env1's properties through configuration class and use an 'environment' property defined in both applicaiton.properties file to make different JavaMailSender Objects in different environments but I also could not make it work because I don't know how to set properties like spring.mail.properties.mail.smtp.starttls.enabl and spring.mail.properties.mail.smtp.auth on my JavaMailSenderImpl object.

I know the reason why I am struggling with this is my lack of skills. Please help me gain some. Any efficient solution to achieve the desired outcome would be appreciated. Thank you.

CodePudding user response:

In this case, spring boot annotation ConditionalOnProperty comes handy. Define a new property email provider type and use that property to drive which beans to be created

  • Related