Wednesday, May 4, 2011

Configuring JBoss mail service to use Gmail as SMTP server

In this post, I'll show how to configure the JBoss mail service to use Gmail as an SMTP server, so that you'll be able to send emails using a valid Gmail account, from within an application that has been deployed in JBoss. 

1° Environment / Prerequisites

  • As in the other posts, I am running JBoss AS 6
  • Any valid Gmail account
2° Mail service configuration


In the deploy directory of your JBoss server, you'll find a file name mail-service.xml (note that this file only exists in the deploy directory of the following server profiles : ALL, DEFAULT and standard). Simply edit this file as shown below :



 
 
 

 
  java:/GMail

  
  someuser@gmail.com

  
  myPassword

  
   
    
    
    
    
   
  
  jboss:service=Naming
 

3° Sending mail : example

On the personal project I am currently working at, mails are sent from a business method within a stateless session bean. Here's the code excerpt that does send the mail : 


Context initCtx;
  try {
   initCtx = new InitialContext();
   Session session = (Session) initCtx.lookup("java:/GMail");
   Message message = new MimeMessage(session);
   
   InternetAddress to[] = new InternetAddress[1];
   to[0] = new InternetAddress("destination@gmail.com");  
   message.setRecipients(Message.RecipientType.TO, to);
   
   message.setSubject("How to send a mail with GMAIL from JBoss AS");
   message.setContent("Hello world", "text/plain");
   Transport.send(message);
  } catch (NamingException e) {
   e.printStackTrace();
  } catch (AddressException e) {
   e.printStackTrace();
  } catch (MessagingException e) {
   e.printStackTrace();
  }
Now, let's take a look at the recipient mailbox : 


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.