Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring 4 mail configuration via java config

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>
like image 228
ilopezluna Avatar asked Jun 07 '14 12:06

ilopezluna


1 Answers

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

like image 82
geoand Avatar answered Nov 18 '22 03:11

geoand