Wednesday, January 4, 2012

How to send an e-mail using Glassfish JavaMail session

Oracle Glassfish 3 application server offers a support for JavaMail API, which make sending and receiving e-mail quite easy and effective.

First you have to create new JavaMail session at Glass fish, login into Glassfish admin console --> JavaMail Sessions --> Click "New"
Then fill the following data:


JNDI Name should be at this syntax mail/<Something>
Mail Host is the SMTP that you will use to send the mail
Default user is the username that defined at your SMTP

Now if your SMTP require an authentication (need password too), move to the button of the add JavaMail session page and add these three properties:
 
  
mail.smtp.password is your password at the SMTP (for the user you defined above)
mail.smtp.auth is ture (SMTP require authentication)
mail.smtp.port is SMTP port number

Done, now you can use this JavaMail session, make Java class similar to this one:

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class SendMail {

    public void sendMail() throws MessagingException, UnsupportedEncodingException {
        try {
            InitialContext ctx = new InitialContext();
            Session mySession = (Session) ctx.lookup("mail/ozienadden@omniya.sy");
            Message msg = new MimeMessage(mySession);
            msg.setSubject("Hello World !");
            msg.setRecipient(RecipientType.TO, new InternetAddress("ozienadden@omniya.sy", "Osama"));
            msg.setFrom(new InternetAddress("automated@omniya.sy", "Virtual Sender"));
            msg.setSentDate(new Date());
            msg.setSubject("Speed Change Request");
            msg.setText("This is my test");
            Transport.send(msg);
        } catch (NamingException ex) {
            Logger.getLogger(SendMail.class.getName()).log(Level.SEVERE, null,ex);
        }
    }
}

No comments:

Post a Comment