2011-10-29

Spring: how to send a mail

Spring has module for email sending. First one need to configure mail sender bean. Actually there are two mail sender implementations. The first one is MailSender that can be used for simple mails. For advanced mails (MIME support) JavaMailSender must be used. It is good practice to divide your configuration into several files, so we'll put mailing configuration into service-mail.xml (or you can choose your own name) and then include that file into main config file. Just for example we'll use gmail as SMTP server so configuration looks like this:



 
    
        
        
        
        
 
        
           
                  true
                  true
               
        
    
 


Spring needs two additional libraries: javax.mail and javax.activation. For maven users: simply add dependency for javax.mail (groupId: javax.mail, artifactId: mail) into your projects pom.xml.

Now we can implement our mailing service:

@Service("mailService")
public class MailServiceImpl implements MailService {
 
    @Autowired
    private JavaMailSender mailSender;
 
    public final void setMailSender(final JavaMailSender p_mailSender) {
        this.mailSender = p_mailSender;
    }
 
    public final JavaMailSender getMailSender() {
        return mailSender;
    }
 
    @Override
    public final void sendMail(final String p_from, final String p_to, final String p_subject, final String p_msg) {
        final MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(final MimeMessage p_mimeMessage) throws Exception {
                final MimeMessageHelper message = new MimeMessageHelper(p_mimeMessage);
                message.setTo(p_to);
                message.setFrom(p_from);
                message.setSubject(p_subject);
                message.setText(p_msg, true); // true means that our text is actually HTML!!!
            }
        };
        mailSender.send(preparator);
    }
 
}

Now we can use our service like this:

mailService.sendMail(fromEmail, toEmail, subject, msg);