Search code examples
springemailspring-bootspring-java-config

Send emails with Spring by using Java annotations


How could I send an email with Spring 4 (and Spring Boot) by using a pure annotation-based approach (according to the Java Configurations rules)?


Solution

  • A simple solution (where you will be using an SMTP server with no authentication) for configuring the email service would by

    @Configuration 
    public class MailConfig {
    
        @Value("${email.host}")
        private String host;
    
        @Value("${email.port}")
        private Integer port;
    
        @Bean
        public JavaMailSender javaMailService() {
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
    
            javaMailSender.setHost(host);
            javaMailSender.setPort(port);
    
            javaMailSender.setJavaMailProperties(getMailProperties());
    
            return javaMailSender;
        }
    
        private Properties getMailProperties() {
            Properties properties = new Properties();
            properties.setProperty("mail.transport.protocol", "smtp");
            properties.setProperty("mail.smtp.auth", "false");
            properties.setProperty("mail.smtp.starttls.enable", "false");
            properties.setProperty("mail.debug", "false");
            return properties;
        }
    }
    

    Spring must be able to resolve the properties email.host and email.port in of the usual ways (in case of Spring Boot the simplest is to put then in application.properties)

    In any class that needs the services of JavaMailSender, just inject with one of the usual ways (such as @Autowired private JavaMailSender javaMailSender)


    UPDATE

    Note that since version 1.2.0.RC1 Spring Boot can auto-configure JavaMailSender for you. Check out this part of the documentation. As you can see from the documentation, almost no configuration is required to get up and running!