Wednesday, July 20, 2011

Spring e-mail example

This is an illustration of how e-mails can be sent using spring framework.

Below is the class written to send e-mails. It's fields, mailSender and emailSubject are injected through spring (The spring configurations can be found at the end of the post). MailSender referred to here is an instance of org.springframework.mail.javamail.JavaMailSenderImpl, the class used to send e-mails in Spring.
In the method send of EmailClient an instance of SimpleMailMessage is created and required attributes such as recipient, sender, e-mail body content, subject and optional parameters like cc, bcc are set. MailSender class's 'send' method is used to send the email.

=========================================================
package com.shyarmal.messaging;

import com.shyarmal.messaging.domain.EmailMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

public class EmailClient {

    private MailSender mailSender;
    private String emailSubject;
    private static final Logger LOGGER = LoggerFactory.getLogger(EmailClient.class);

    public void send(EmailMessage message) {
        try {
            if(LOGGER.isDebugEnabled()) {
                LOGGER.debug("email message [{}]", message);
            }
            SimpleMailMessage mailMessage = new SimpleMailMessage();
            mailMessage.setSubject(emailSubject);
            mailMessage.setText(message.getText());
            mailMessage.setFrom(message.getFrom());
            mailMessage.setTo(message.getTo());
            if(message.getCc() != null && !message.getCc().isEmpty()) {
                mailMessage.setCc(message.getCc());
            }
            mailSender.send(mailMessage);
            LOGGER.info("email was sent to {} successfully.", message.getTo());
        } catch(Exception e) {
            LOGGER.error(String.format("Message sending failed for [%s]", message), e);
        }
    }

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setEmailSubject(String emailSubject) {
        this.emailSubject = emailSubject;
    }
   
}

=========================================================

The following class is merely a bean, which is used to hold the parameters of the message. It's feilds are self-explanatory.
=========================================================


package com.shyarmal.messaging.domain;


public class EmailMessage {

    private String to;
    private String from;
    private String text;
    private String cc;
    private String correlationId;

    public EmailMessage(String to, String from, String text) {
        this.to = to;
        this.from = from;
        this.text = text;
    }
   
    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getCc() {
        return cc;
    }

    public void setCc(String cc) {
        this.cc = cc;
    }

    @Override
    public String toString() {
        return String.format("message: to[%s], from[%s], text[%s]",
                to, from, text);
    }

}

=========================================================

EmailClient can be used as follows.
=========================================================
String emailText = "This is my email body";
EmailMessage eMessage = new EmailMessage("abc@gmail.com", "xyz@gmail.com", emailText);
emailClient.send(eMessage) ; // suppose emailClient is an instance of EmailClient

=========================================================

Required properties of the mailSender are set through Spring as follows. The properties are obtained from a file, mailing.properties. It's contents are further down in the post.
=========================================================

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"
    p:host="${mail.sender.host}"
    p:port="${mail.sender.port}"
    p:username="${mail.sender.username}"
    p:password="${mail.sender.password}"
    p:protocol="${mail.sender.protocol}"
    p:javaMailProperties-ref="mailProperties"/>

<bean id="emailClient" class="com.shyarmal.messaging.EmailClient"
    p:mailSender-ref="mailSender"
    p:emailSubject="${email.subject}"/>

<util:properties id="mailProperties">
        <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
        <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
        <prop key="mail.smtp.quitwait">${mail.smtp.quitwait}</prop>
</util:properties>

<context:property-placeholder location="classpath:mailing.properties"/>
=========================================================

mailing.properties contents 
=========================================================
email.subject = my email subject
mail.sender.host = smtp.gmail.com
mail.sender.port = 587
mail.sender.username =xxxxxxxx@xxxx.xxx
mail.sender.password = xxxxxx@xxxxx
mail.sender.protocol = smtp
mail.smtp.auth = true
mail.smtp.starttls.enable = true
mail.smtp.quitwait = false

thanks,
Shyarmal.

No comments:

Post a Comment