Ignasi
Ignasi

Reputation: 6185

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>

Upvotes: 10

Views: 16974

Answers (2)

ABHAY JOHRI
ABHAY JOHRI

Reputation: 2156

@Configuration 
public class AppConfig {

    @Value("${mail.host}")
    private String host;


    @Bean
    public JavaMailSender emailService() {
        JavaMailSender javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setHost(host);
        return javaMailSender;
    }



@Component
public class EmailServiceImpl implements EmailService {

    @Autowired
    public JavaMailSender emailSender;

    public void sendSimpleMessage( String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage(); 
        message.setTo(to); 
        message.setSubject(subject); 
        message.setText(text);
        emailSender.send(message);
    }
}

Upvotes: 0

geoand
geoand

Reputation: 64039

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

Upvotes: 20

Related Questions