Saturday, May 28, 2011

Upload Email Using IMAP

Java mailing & IMAP


This post describes the use of JAVA mailing API to access the mail account using IMAP protocol and upload the simple Email to the specific inbox folder.
Email servers and other mail transfer agents uses Simple Mail Transfer Protocol (SMTP) to send and receive Email messages. A client mail application typically uses SMTP for sending messages to a mail server for relaying whereas either the Post Office Protocol (POP) or the Internet Message Access Protocol (IMAP) to access their mail box accounts on a mail server.
Let’s create a simple Java class which uploads the email to the inbox. We can’t sent mail using IMAP for mail transfer we required SMTP.
Code snippet 1
This class contains most of the configurable parameters which are required to configure the IMAP and other Email configuration parameters.
Mail body supports the UTF-8 character-set which is specified in message content & header part.
IMAPAuthenticator handles the Authentication for the IMAP and mail session created by passing authentication token to the Session.getInstance method.
package com.ashish.imap;

import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;

/**
 * This class uses the IMPA protocol to upload the newly created mail message into a specify mail folder.
 *
 * <pre>
 * Usage:
 * Map sendParameters = new HashMap();
 * sendParameters.put(MAIL_TO,mailTo);
 * sendParameters.put(MAIL_FROM,replyTo);
 * sendParameters.put(MAIL_CONTENT,mailContent);
 * sendParameters.put(MAIL_IMAP_HOST,strMailHost);
 * sendParameters.put(MAIL_IMAP_PORT,strMailPort {993});
 * sendParameters.put(MAIL_IMAP_AUTH_USER,strAuthUser);
 * sendParameters.put(MAIL_IMAP_AUTH_PASSWORD,strAuthPassword); 
 * sendParameters.put(IMAP_UPLOAD_FOLDER_NAME,strUploadFolderName {inbox}); 
 * sendParameters.put(MAIL_IMAP_SOCKETFACTORY_PORT,strSocketFactoryPort{Same  as MAIL_IMAP_PORT ,993} ); 
 * sendParameters.put(MAIL_IMAP_SSL_PROTOCOLS,strSSLProtocolsName {SSL}); 
 * IMAPMailClient.uploadMailMessage(sendParameters);
 *
 * </pre>
 *
 * @author Ashish.Chudasama
 */
public final class IMAPMailClient
{

    /*
     * More configurable parameter information can be obtain from
* http://technology-related.com/products/javamail/javadocs/com/sun/mail/imap/package-summary.html
     */
  public static final String MAIL_CONTENT = "mail.body";
  public static final String MAIL_SUBJECT = "mail.subject";
  public static final String MAIL_CC = "mail.cc";
  public static final String MAIL_TO = "mail.to";

public static final String MAIL_IMAP_AUTH_PLAIN_DISABLE =   "mail.imap.auth.plain.disable";

public static final String MAIL_IMAP_AUTHENTICATION_REQUIRED = "imap_authentication_required";

  public static final String MAIL_IMAP_PORT = "mail.imap.port";

  public static final String MAIL_FROM = "mail.from";

public static final String MAIL_STORE_PROTOCOL =  "mail.store.protocol";
 
  public static final String MAIL_IMAP_HOST = "mail.imap.host";

  public static final String IMAP_UPLOAD_FOLDER_NAME =    "imap.upload.mail.folder";

    public static final String MAIL_IMAP_DEBUG = "mail.imap.debug";// "mail.imap.debug","true"

    public static final String MAIL_IMAP_SSL_PROTOCOLS = "mail.imap.ssl.protocols";// SSL

    public static final String MAIL_IMAP_SOCKETFACTORY_PORT = "mail.imap.socketFactory.port";// SSL


    public static final String MAIL_IMAP_AUTH_USER = "mail.imap.user";
    public static final String MAIL_IMAP_AUTH_PASSWORD = "mail.imap.password";

    /**
* sendMailMessage uses javax.mail APIs for sending mails. Sends mail to e-mail address mentioned in mailTo params.
     *
     * @param mapMailInfo
     * @return -1 if mailing fails.
     */
    /**
     * @param mapMailInfo
     * @return
     */
    public static int uploadMailMessage(Map<?,?> mapMailInfo)
    {
        /**
* SimpleAuthenticator is used to do simple authentication when the SMTP server requires it.
         */
        class IMAPAuthenticator extends javax.mail.Authenticator
        {
            String username = "";
            String password = "";

public IMAPAuthenticator(String username, String password)
            {
                this.username = username;
                this.password = password;
            }

public PasswordAuthentication getPasswordAuthentication()
            {
 return new PasswordAuthentication(username, password);
            }
        }


        int mailSentStatus = 0;

String strMailHost = (String) mapMailInfo.get(MAIL_IMAP_HOST);
       
String strMailPort = (String) mapMailInfo.get(MAIL_IMAP_PORT);

        if (strMailPort == null || "".equals(strMailPort.trim()))
        {
            strMailPort = "993"; // default port
        }

String strProtocol = (String) mapMailInfo.get(MAIL_STORE_PROTOCOL);
       
if (strProtocol == null || "".equals(strProtocol.trim()))
        {
            strProtocol = "imap"; // default protocol
        }
String strAuthenticate = (String) mapMailInfo.get(MAIL_IMAP_AUTH_PLAIN_DISABLE);
       
if (strAuthenticate == null || "".equals(strAuthenticate.trim()))
        {
            strAuthenticate = "true";
        }

       
String strImapAuthUser = (String) mapMailInfo.get(MAIL_IMAP_AUTH_USER);
       
String strImapAuthPassword = (String) mapMailInfo.get(MAIL_IMAP_AUTH_PASSWORD);

       
String strMailFrom = (String) mapMailInfo.get(MAIL_FROM);

  // expect list of recipients instead...
      
 String strMailTo = (String) mapMailInfo.get(MAIL_TO);
       
String strCC = (String) mapMailInfo.get(MAIL_CC);

      
 String strMailSubject = (String) mapMailInfo.get(MAIL_SUBJECT);
       
if (strMailSubject == null)
        {
            strMailSubject = "";
        }
       
String strMailMessage = (String) mapMailInfo.get(MAIL_CONTENT);

        String strImapDebug = (String) mapMailInfo.get(MAIL_IMAP_DEBUG);
        if (strImapDebug == null || "".equals(strImapDebug.trim()))
        {
            strImapDebug = "true";
        }

        String strImapSSLProtocols = (String) mapMailInfo.get(MAIL_IMAP_SSL_PROTOCOLS);
        if (strImapSSLProtocols == null || "".equals(strImapSSLProtocols.trim()))
        {
            strImapSSLProtocols = "SSL";
        }

        String strImapSocketFactoryPort = (String) mapMailInfo.get(MAIL_IMAP_SOCKETFACTORY_PORT);
        if (strImapSocketFactoryPort == null || "".equals(strImapSocketFactoryPort.trim()))
        {
            strImapSocketFactoryPort = "993";
        }

        String isAuthenicationRequired = (String) mapMailInfo.get(MAIL_IMAP_AUTHENTICATION_REQUIRED);
        if (isAuthenicationRequired == null || "".equals(isAuthenicationRequired.trim()))
        {
            isAuthenicationRequired = "true";
        }

        String strImapUploadFolder = (String) mapMailInfo.get(IMAP_UPLOAD_FOLDER_NAME);
        if (strImapUploadFolder == null || "".equals(strImapUploadFolder.trim()))
        {
            strImapUploadFolder = "inbox";
        }

        int msgReturn = -1;
        try
        {
            Properties properties = new Properties();
            properties.put(MAIL_IMAP_HOST, strMailHost);
            properties.put(MAIL_STORE_PROTOCOL, strProtocol);
            properties.put(MAIL_IMAP_PORT, strMailPort);
            properties.put(MAIL_IMAP_AUTH_PLAIN_DISABLE, strAuthenticate);

properties.setProperty(MAIL_IMAP_DEBUG, strImapDebug);

properties.setProperty(MAIL_IMAP_SSL_PROTOCOLS, strImapSSLProtocols);
            properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.imap.socketFactory.fallback", "false");

properties.setProperty(MAIL_IMAP_SOCKETFACTORY_PORT, strImapSocketFactoryPort);

            Session session = null;
            if (isAuthenicationRequired.equalsIgnoreCase("true"))
            {
Authenticator auth = new IMAPAuthenticator(strImapAuthUser, strImapAuthPassword);
                session = Session.getInstance(properties, auth);
            }
            else
            {
                session = Session.getInstance(properties, null);
            }

            Message message = new MimeMessage(session);

            String[] arrMailTo = strMailTo.split(",");

InternetAddress[] addresses = new InternetAddress[arrMailTo.length];
            for (int i = 0; i < arrMailTo.length; i++)
            {
addresses[i] = new InternetAddress(arrMailTo[i].trim());
            }
            message.setRecipients(Message.RecipientType.TO, addresses);

            if (strCC != null)
            {
                String[] arrMailCc = strCC.split(",");
InternetAddress[] ccTo = new InternetAddress[arrMailCc.length];
              
 for (int i = 0; i < arrMailCc.length; i++)
                {
ccTo[i] = new InternetAddress(arrMailCc[i].trim());
                }
                message.setRecipients(Message.RecipientType.CC, ccTo);
            }

            message.setFrom(new InternetAddress(strMailFrom));
            message.setSubject(strMailSubject);
            //following setting required to support UTF-8                                                                                        //characterset
message.setContent( strMailMessage, "text/html; charset=utf-8" );
message.setHeader("Content-Type","text/plain; charset=\"utf-8\"");
message.setHeader("Content-Transfer-Encoding", "quoted-printable");
           

            // create the message part
            BodyPart messageBodyPart = new MimeBodyPart();

            // Fill the message
            messageBodyPart.setText(strMailMessage);

            session.setDebug(true);

javax.mail.Store store = session.getStore(strProtocol);
            store.connect();

            Folder inbox = store.getFolder(strImapUploadFolder);
            inbox.open(Folder.READ_WRITE);
            inbox.appendMessages(new Message[] { message });
            inbox.close(true);

        }
        catch (Exception e)
        {
            mailSentStatus = -1;
System.out.println("Exception:Error in Uploading Message File");
            e.printStackTrace();
            return msgReturn;
        }
        return mailSentStatus;

    }

}


Code snippet 2
The stub class demonstrates the use of IMAP upload mail functionality. For the simplicity and easy configurability most of the configurable parameter is externalized to mail_config.property so that configurable parameter configure easily without changing demo-stub class.
package com.ashish.imap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * Demo Stub class.
 * @author ashish.chudasama
 */
public class IMAPStubclass
{
    // Holds the configuration details.
    private static Map<String, String> gtConfigMap = new HashMap<String, String>();

    public IMAPStubclass()
    {
        initializeExternalConfigFile();
    }

    /**
     * This Functions Read The Configuration Information from gt_mail_config.properties file.
     */
    public void initializeExternalConfigFile()
    {
        try
        {
            File file = new File("");
            System.out.println(file.getAbsolutePath());
            FileInputStream inputStream = new FileInputStream(file.getAbsolutePath() + "/mail_config.properties");
            ResourceBundle bundle = new PropertyResourceBundle(inputStream);
            Enumeration<String> keys = bundle.getKeys();
            while (keys.hasMoreElements())
            {
                String strKey = (String) keys.nextElement();
                String strData = (String) bundle.getString(strKey);
                gtConfigMap.put(strKey, strData);
            }
        }
        catch (FileNotFoundException e)
        {
            System.err.println("External Config File Not Found");
            e.printStackTrace();

        }
        catch (IOException e)
        {
            System.err.println("Unable to read external config file");
            e.printStackTrace();
        }
        catch (Exception e)
        {
            System.err.println("External Config properties have not been read");
            e.printStackTrace();
        }

    }

    /**
     * This method demonstrate UPLOADING of mail to specified mail folder using IMAP.
     */
    public static void main(String[] args)
    {
        IMAPStubclass stubclass = new IMAPStubclass();
        stubclass.uploadMail();

    }

    /**
     * Function Upload mail to specified mail box.
     */
    private void uploadMail()
    {
        Map<String, String> sendParameters = new HashMap<String, String>();
        sendParameters.put(IMAPMailClient.MAIL_TO, gtConfigMap.get(IMAPMailClient.MAIL_TO));
        sendParameters.put(IMAPMailClient.MAIL_FROM, gtConfigMap.get(IMAPMailClient.MAIL_FROM));
        sendParameters.put(IMAPMailClient.MAIL_CONTENT, gtConfigMap.get(IMAPMailClient.MAIL_CONTENT));
        sendParameters.put(IMAPMailClient.MAIL_IMAP_HOST, gtConfigMap.get(IMAPMailClient.MAIL_IMAP_HOST));
        sendParameters.put(IMAPMailClient.MAIL_IMAP_PORT, gtConfigMap.get(IMAPMailClient.MAIL_IMAP_PORT));
        sendParameters.put(IMAPMailClient.MAIL_IMAP_AUTH_USER, gtConfigMap.get(IMAPMailClient.MAIL_IMAP_AUTH_USER));
        sendParameters.put(IMAPMailClient.MAIL_IMAP_AUTH_PASSWORD, gtConfigMap.get(IMAPMailClient.MAIL_IMAP_AUTH_PASSWORD));
        sendParameters.put(IMAPMailClient.IMAP_UPLOAD_FOLDER_NAME, gtConfigMap.get(IMAPMailClient.IMAP_UPLOAD_FOLDER_NAME));
        sendParameters.put(IMAPMailClient.MAIL_IMAP_SOCKETFACTORY_PORT, gtConfigMap.get(IMAPMailClient.MAIL_IMAP_SOCKETFACTORY_PORT));
        sendParameters.put(IMAPMailClient.MAIL_IMAP_SSL_PROTOCOLS, gtConfigMap.get(IMAPMailClient.MAIL_IMAP_SSL_PROTOCOLS));
        sendParameters.put(IMAPMailClient.MAIL_SUBJECT, gtConfigMap.get(IMAPMailClient.MAIL_SUBJECT));
        IMAPMailClient.uploadMailMessage(sendParameters);
    }
}


Code snippet 3
################################################################
# Description    This is the Mail configuration file for IMAP Mail Demo.
# Created By:     Ashish.Chudasama
################################################################

mail.imap.auth.plain.disable=true
mail.imap.debug=true
imap_authentication_required=true
mail.store.protocol=imap
mail.imap.ssl.protocols=ssl
mail.imap.socketFactory.port=993
mail.imap.port=993
mail.imap.host=imap.gmail.com

## IMAP authentication credentials
mail.imap.user=MYUSERID
mail.imap.password=MYpassword
#upload folder name
imap.upload.mail.folder=inbox
#mail information
mail.cc=Mail_CC_Address
mail.to=Mail_TO_Address
mail.from=Mail_FROM_Address
mail.subject=IMAP MAIL DEMO
mail.body=This is Test code....               

Output:




Click here to download source code.                                                                   

1 comment: