Email enabling Spring Applications.

Spring Framework

Gmail

Using gmail smtp server, JavaMail and Spring IOC, we can quickly put together a simple mail sending application, without any SMTP server installation. Check this out for a detailed description of using gmail as smtp server. Thanks to Enrico for blogging smtp spring configuration.

Assuming you have used Spring before, here is a short tutorial:

  1. Add mail.jar from JavaMail project to build path.
  2. In spring bean configuration file add:
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com"/>
    <property name="username" value="${gmail_username}"/>
    <property name="password" value="${gmail_password}"/>
    <property name="javaMailProperties">
    <props>
    <prop key="mail.smtp.auth">true</prop>
    <prop key="mail.smtp.starttls.enable">true</prop>
    </props>
    </property>
    </bean>
    
    <!-- this is a template message that we can pre-load with default state -->
    <bean id="templateMessage" class="org.springframework.mail.SimpleMailMessage">
    <!-- The from field is overwritten by gmail to your gmail ID.
    Go to Gmail Account Settings to choose default outgoing mail ID. -->
    <property name="from" value="notify@abcd-xyz.com"/>
    <property name="subject" value="Mail Notification."/>
    </bean>
  3. Create a class MailNotifier where you send mails.
    import org.springframework.mail.MailException;
    import org.springframework.mail.MailSender;
    import org.springframework.mail.SimpleMailMessage;
    
    import com.abcd.beans.Member;
    
    /**
    * @author gubbi
    *
    */
    public class MailNotifier {
    private MailSender mMailSender;
    private SimpleMailMessage mTemplateMessage;
    
    public void sendNotification(Member pMember) {
    SimpleMailMessage message = new SimpleMailMessage(mTemplateMessage);
    
    message.setText("Dear " + pMember.getFirstName()
    + ",\nSending test notification.");
    message.setTo(pMember.getEmail());
    try{
    mMailSender.send(message);
    }
    catch(MailException ex) {
    ex.printStackTrace();
    }
    }
    
    /**
    * @param pMailSender the mailSender to set
    */
    public void setMailSender(MailSender pMailSender) {
    mMailSender = pMailSender;
    }
    
    /**
    * @param pTemplateMessage the templateMessage to set
    */
    public void setTemplateMessage(SimpleMailMessage pTemplateMessage) {
    mTemplateMessage = pTemplateMessage;
    }
    }
  4. Add spring bean configuration for MailNotifier class:
    <bean id="mailNotifier" class="com.abcd.modules.MailNotifier">
    <property name="mailSender" ref="mailSender"/>
    <property name="templateMessage" ref="templateMessage"/>
    </bean>
  5. This is it  :-)

Check out Spring Reference for details about sending mails with attachments and using html templates for mail content. Let me know other methods of doing the same.

Tags: , , , ,