How to Send E-mail using Spring and JavaMail

In this article, we will show you an example that will demonstrate how to send e-email using Spring and JavaMail. The following additional jars to be on the classpath of your application in order to be able to use the Spring Framework's email library.
  • The JavaMail mail.jar library
  • The JAF activation.jar library
The Spring Framework provides a helpful utility library for sending email that shields the user from the specifics of the underlying mailing system and is responsible for low level resource handling on behalf of the client.




Basic MailSender and SimpleMailMessage usage

Let us assume that there is a requirement stating that an email message with an order number needs to be generated and sent to a customer placing the relevant order.

public class SimpleOrderManager implements OrderManager {
  private MailSender mailSender;
  private SimpleMailMessage templateMessage;

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

  public void setTemplateMessage(SimpleMailMessage templateMessage) {
    this.templateMessage = templateMessage;
  }

  public void placeOrder(Order order) {
    // Do the business calculations...
    // Call the collaborators to persist the order...
    // Create a thread safe "copy" of the template message and customize it
    SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
    msg.setTo(order.getCustomer().getEmailAddress());
    msg.setText("Dear " + order.getCustomer().getFirstName() + order.getCustomer().getLastName()
        + ", thank you for placing order. Your order number is " + order.getOrderNumber());
    try {
      this.mailSender.send(msg);
    } catch (MailException ex) {
      // simply log it and go on...
      System.err.println(ex.getMessage());
    }
  }
}

























Find below the bean definitions for the above code:

<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="customerservice@mycompany.com" />
  <property name="subject" value="Your order" />
</bean>
<bean id="orderManager" class="com.mycompany.businessapp.support.SimpleOrderManager">
  <property name="mailSender" ref="mailSender" />
  <property name="templateMessage" ref="templateMessage" />
</bean>







No comments:

Post a Comment