Is there some example of how MailSender can be configured via java config? All examples that I've seen uses xml to create needed beans:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.mycompany.com"/>
</bean>
<!-- this is a template message that we can pre-load with default state -->
<bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="[email protected]"/>
<property name="subject" value="Your order"/>
</bean>
The code you posted (along with some small improvements to make it more configurable) would be transformed into the following Java config:
@Configuration
public class MailConfig {
@Value("${email.host}")
private String host;
@Value("${email.from}")
private String from;
@Value("${email.subject}")
private String subject;
@Bean
public JavaMailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost(host);
return javaMailSender;
}
@Bean
public SimpleMailMessage simpleMailMessage() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom(from);
simpleMailMessage.setSubject(subject);
return simpleMailMessage;
}
}
You should also be aware of the fact that Spring Boot (which you have not mentioned whether or not you are using) can auto-configure an JavaMailSender
for you. Check out this part of the documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With