Friday, June 15, 2012

How to send an Email From an ADF Application Deployed on WebLogic Server

In this article, I'll show you a practical exemple about how to send an Email from an ADF application deployed on Weblogic. The following image shows the UI page used in our sample application to send Emails:


Here are all the steps to send a Email using Java Mail API:

1. First, download JavaMail API zip (here), and add the mail.jar as a library to your project :




2. Create a new Mail Session and set its JNDI Name and its appropriate properties :

To configure a Mail Session, open the Weblogic server Home page, and click on the Mail Session link:


Click on the new button to create a new Mail Session:


Add  a name and JNDI url to your new Mail Session:


Enter details in the JavaMail Properties field as the following exemple:
mail.smtp.auth=true
mail.debug=true
mail.smtp.host=smtp.gmail.com
mail.smtp.user=hazsiwemar@gmail.com (your Email adress)
mail.smtp.password=xxxxxxxxx  (your Email password)
mail.transport.protocol=smtp
mail.smtp.port=465
mail.disable=false
mail.verbose=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

Then click Next and select the check box:



3. Access the mail session using JNDI then fetch the properties set in the mail session in your code to send the e-mail.

After entering the destination adress, the subject, and the Email content in the UI page presented at the beginning of this article, The Email will be sent by clicking on Send Button which executes an Action Listener method on the managed bean.
In the following, I'll expose to you the most important parts of the java code inside the managed Bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.sun.mail.smtp.SMTPTransport;
import java.util.Date;
import java.util.Properties;
import javax.faces.event.ActionEvent;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
...
    private String destination ;
    private String subject ;
    private String content ;
...
public void sendMail(ActionEvent actionEvent) throws Exception{        
            InitialContext ic = new InitialContext();
            Session session = (Session) ic.lookup("mail/MyEmailSession");
            Properties props = session.getProperties();
            System.out.println("Email session properties list: ");
            props.list(System.out);
            String  to = destination;
            if(to==null || to.equals(""))
                to = "benkhalfallahhazem@gmail.com";
         
            if(subject==null || subject.equals(""))
                subject = "Test sending mails";
            String mailhost = props.getProperty("mail.smtp.host");
            System.out.println("host = " + mailhost);
            String user = props.getProperty("mail.smtp.user");
            System.out.println("user = " + user);
            String password = props.getProperty("mail.smtp.password");
            System.out.println("password = " + password);
            String protocol = props.getProperty("mail.transport.protocol");
            System.out.println("protocol = " + protocol);
         
            String authorization = props.getProperty("mail.smtp.auth");
            String mailDisabled = props.getProperty("mail.disable");
            String verboseProp = props.getProperty("mail.verbose");
            String debugProp = props.getProperty("mail.debug");
         
            boolean sentDisabled = false;
            if(mailDisabled.equals("true"))
                sentDisabled = true;
         
            if(!sentDisabled){
             
                boolean auth = false;
                if(authorization.equals("true"))
                    auth = true;
             
                boolean verbose = false;
                if(verboseProp.equals("true"))
                    verbose = true;
     
                String mailer = "smtpsend";
             
                if(debugProp.equals("true"))
                    session.setDebug(true);
                else
                    session.setDebug(false);
     
                System.out.println("session initialized.");
                   
                Message msg = new MimeMessage(session);
             
                msg.setFrom();    
             
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
             
                System.out.println("recipient set.");
             
                msg.setSubject(subject);
                msg.setText(content);
     
                msg.setHeader("X-Mailer", mailer);
                msg.setSentDate(new Date());
     
                System.out.println("Metadata set.");
     
                SMTPTransport t = (SMTPTransport)session.getTransport(protocol);
     
                System.out.println("Gettting Transport.");
     
                try {
                    System.out.println("Before connect via authorization.");
                    t.connect(mailhost, user, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                    System.out.println("message sent.");
                } finally {
                        if (verbose)
                            System.out.println("Response: " + t.getLastServerResponse());
                        t.close();
                }
           
                System.out.println("\nMail was sent successfully.");
            }else{
                System.out.println("Mail Sending is disabled.");
            }
         
        }
...
//Getters and setters of private destination , subject  and content properties
The sendMail() action listener accesses the Mail Session already defined inside Weblogic server using the JNDI URL "mail/MyEmailSession".

Now you can run your application. After entering the details, when you click the Send button, the Email is send, and here is how that mail looks like:



If the provider doesn't support SSL for SMTP connections, then you will hit the following error:
DEBUG SMTP: exception reading response: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Exception in thread "main" javax.mail.MessagingException: Exception reading response;
nested exception is:
  javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
To avoid it, remove mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory property from mail session and it will work fine.


You can download this sample from the link below:
sendMail.rar (664ko)