Posted by : Munish Gogna Saturday, April 9, 2011

Hi everyone, First of all thanks to Anna Hazare and all who have really fought for lokpal bill.

Today's article is about sending Thanks email to Anna Hazare for his tremendous dedication towards our great nation, it's about setting up SMTP server to send emails from your application hosted on JBOSS Application server.


The focus will be on the Anna Hazare and Jboss setup rather than providing a full fledged Email Service.


Our application will be sending emails over gmail SMTP server.
Please pay attention to comments from now onwards through out this article. :)

Maven dependency : Here is a skelton of our maven project.

 4.0.0
 com.mg.poc.email
 JbossMail
 0.0.1-SNAPSHOT
 ejb
 A Simple project to send Emails using Gmail (service running in JBOSS) 

 
  
   Munish Gogna
   gognamunish@gmail.com
   www.twitter.com\munishgogna
  
 

 
 
  
   javaee
   javaee-api
   5
   provided
  

 
 

  ${basedir}/src
  
   
    ${basedir}/src
    
     **/*.java
    
   
  
  
   
    org.apache.maven.plugins
    maven-ejb-plugin
    
     3.0
    
   
   
    maven-compiler-plugin
    
     1.5
     1.5
    
   
  
 




STEP 1 Define our Gmail based SMTP mail service that we will use in our sample application.

SERVER\deploy\mail-service.xml : Create the service definition as shown below:



  
  
  

  
    java:/GMail
    gognamunish@gmail.com
    
    XXXXXX
    
      
       
            
            
      
      
      
            
            
         
    
    jboss:service=Naming
  

After placing this file in deploy folder, you should see following logs in server.log
15:40:49,985 INFO [MailService] Mail Service bound to java:/GMail

STEP 2 Let's build our sample EJB based application that will consume this service to send emails, time to define our remote interface.

package com.mg.poc.email;

import javax.ejb.Remote;

/**
 * Simple interface for our Mail Service.
 * 
 * @author Munish Gogna
 * 
 */
@Remote
public interface MailSender {

 /**
  * Sends mail using GMAIL Service.
  * 
  * @param envelope
  *            envelope to send
  */
 void sendMail(MailEnvelope envelope) throws GmailException;

}

The Envelope class is a simple class that holds regular stuff we need to send email. It is defined as :

package com.mg.poc.email;

import java.io.Serializable;

/**
 * Contains regular email stuff (with some defaults).
 * 
 * @author Munish Gogna
 *
 */
public class MailEnvelope implements Serializable {

 private static final long serialVersionUID = 1L;
    
 private String subject ="thanks Anna Hazare";
 private String to;
 private String from ="gognamunish@gmail.com";
 private String body ="Anna you are great. We the people of india have won the 1st step against the Govt. & feeling real freedom only Bcoz of you. - love you !!!!";

 /** setters/getters omitted */

}
Now as we have defined the interface for our Email Service, let's provide the implementation of the same.
package com.mg.poc.email;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Bean to manage simple email functionality.
 * 
 * @author Munish Gogna
 * 
 */
@Stateless
public class MailService implements MailSender {

 /**
  * This resource is defined in mail-service.xml file.
  */
 @Resource(mappedName = "java:/GMail", description = "jndi mapping for our simple mail service")
 Session mailSession;

 public void sendMail(MailEnvelope envelope) throws GmailException {
  
  if(envelope == null){
   throw new GmailException("envelope is null");
  }
  
  Message simpleMessage = new MimeMessage(mailSession);

  try {
   simpleMessage.setFrom(createInternetAddress(envelope.getFrom()));
   simpleMessage.setRecipient(RecipientType.TO, createInternetAddress(envelope.getTo()));
   simpleMessage.setSubject(envelope.getSubject());
   simpleMessage.setText(envelope.getBody());

   Transport.send(simpleMessage);
  } catch (MessagingException e) {
   throw new GmailException(e.getMessage());
  }

 }

 private Address createInternetAddress(String address) throws GmailException {
  try {
   return new InternetAddress(address);
  }catch (AddressException e) {
   throw new GmailException(e.getMessage());
  }
 }

}

That's all we are done.
> Generate jar - mvn clean install
> copy JbossMail-0.0.1-SNAPSHOT.jar to deploy folder.
> server logs should show binding of our EJB Stateless session beans as shown below:

15:41:33,403 INFO [EJBContainer] STARTED EJB: com.mg.poc.email.MailService ejbName: MailService
15:41:33,412 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

MailService/remote - EJB3.x Default Remote Business Interface


Finally we will test the service to make sure it actually sends email.

package com.mg.poc.email.test;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import com.mg.poc.email.MailEnvelope;
import com.mg.poc.email.MailSender;

/**
 * Simple Test.
 * 
 * @author Munish Gogna
 * 
 */
public class TestMail {

 public static void main(String[] args) throws Exception {
  Properties properties = new Properties();

  properties.put("java.naming.factory.initial",
    "org.jnp.interfaces.NamingContextFactory");
  properties.put("java.naming.factory.url.pkgs",
    "org.jboss.naming:org.jnp.interfaces");
  properties.put("java.naming.provider.url", "localhost");
  Context context;
  try {
   context = new InitialContext(properties);
   MailSender beanRemote = (MailSender) context
     .lookup("java:MailService/remote");

   MailEnvelope envelope = new MailEnvelope();
   envelope.setTo("anna.hazare@gmail.com");

   beanRemote.sendMail(envelope);
   System.out.println("mail sent successfully !!!");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Note : In case you want to run this client, make sure you add all the required client libraries in the classpath, do one thing add all jars in JBOSS_HOME/client folder to classpath OR try adding following dependency in the pom file.


jboss
jbossall-client
${jboss.version}
${jboss.home}/client/jbossall-client.jar
system

Creating client jars and managing dependencies\jndi lookups can be nightmare sometimes, not some times but most of the times, please do share your thoughts on the same.

To end discussion on this topic I would once again like to thank everyone who stood with Hazare to fight against corruption.

Thanks.

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Popular Post

Labels

enums (1) java (2) JAX-RS (1) JPA (1) mysql (1) request 2 (1) RESTful (1) sphinx (1) tomcat (1) web service (2) ws (2)