Creating the beans
Spring boot will only initialize one JavaMailSender as soon as it finds the spring.mail.* properties. If you need multiple ones, you have to define these beans by yourself. If you only need the properties host, port, username and password, you could use this simple configuration:
@Configuration
public class MailConfiguration {
@Bean
@ConfigurationProperties(prefix = "spring.mail.primary")
public JavaMailSender primarySender() {
return new JavaMailSenderImpl();
}
@Bean
@ConfigurationProperties(prefix = "spring.mail.secondary")
public JavaMailSender secondarySender() {
return new JavaMailSenderImpl();
}
}
However, this will not work if you also want to configure spring.mail.properties.* as well. In order to do that, your configuration will be a bit more complex, since you'll have to do the following:
- Create two beans of
MailProperties using the same @ConfigurationProperties as you can see above.
- Use the
MailProperties in a similar way as Spring boot does within MailSenderPropertiesConfiguration.
Configuration
After that, you can use the spring.mail.primary.* properties and spring.mail.secondary.* properties as you're used to. For example:
spring.mail.primary.host=host1
spring.mail.primary.port=port1
spring.mail.primary.username=username1
spring.mail.primary.password=password1
spring.mail.secondary.host=host2
spring.mail.secondary.port=port2
spring.mail.secondary.username=username2
spring.mail.secondary.password=password2
Usage
After that, you can autowire both primarySender and secondarySender. Make sure to use the @Qualifier annotation to tell Spring which is which:
@Service
public class MailService {
private JavaMailSender primarySender;
private JavaMailSender secondarySender;
public MailService(
@Qualifier("primarySender") JavaMailSender primarySender,
@Qualifier("secondarySender") JavaMailSender secondarySender) {
this.primarySender = primarySender;
this.secondarySender = secondarySender;
}
}