Sunday, November 18, 2012

POP3 email polling


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage.RecipientType;

import com.orga.application.vo.EmailVO;
import com.orga.utility.loggers.Logger;
import com.orga.utility.loggers.LoggerFactory;
import com.orga.utility.utils.CommonUtils;
import com.orga.utility.utils.DateUtils;
import com.sun.mail.pop3.POP3SSLStore;
/**
 * This Class represents the global
 * Email Interaction and pop 3 configuration
 * to read the emails..
 *
 * @version 0.1, 05 Sept 2012 - Base version
 *
 */
public class EmailIntegration {
    /**
     * The logger instance for this class.
     */
    private static final Logger LOGGER = LoggerFactory.
    getInstance().getLogger(EmailIntegration.class);
    /**
     * Represent the Mail session object.
     */
    private Session session = null;
    /**
     * Represent the store Object.
     */
    private Store store = null;
    /**
     * Represent the Folder object of mail.
     */
    private Folder folder;
    private String username, password;
   
   
    /**
     * Closing Folder method
     *
     * @throws Exception
     */
    public void closeFolder() throws Exception {
        folder.close(false);
    }
    /**
     * Method to get the Message Count.
     *
     * @return no of messages<tt>int</tt>.
     *
     * @throws Exception
     */
    public int getMessageCount() throws Exception {
        return folder.getMessageCount();
    }
    /**
     * Method to get the unread Message Count.
     *
     * @return no of messages<tt>int</tt>.
     *
     * @throws Exception
     */
    public int getUnreadMessageCount() throws Exception {
        return folder.getUnreadMessageCount();
    }
    /**
     * Method to get the new Message Count.
     *
     * @return no of messages<tt>int</tt>.
     *
     * @throws Exception
     */
    public int getNewMessageCount() throws Exception {
        return folder.getNewMessageCount();
    }

    public void disconnect() throws Exception {
        store.close();
    }
    public void setUserPass(String username, String password) {
        this.username = username;
        this.password = password;
    }
    /**
     * Method represent the mail Connection.
     *
     * @throws Exception throws exception in
     * case not able to connect.
     */
    public void connect() throws Exception {
        try {
            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            Properties pop3Props = new Properties();
            pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
            pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
            pop3Props.setProperty("mail.pop3.port", "995");
            pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
            pop3Props.setProperty("javax.net.ssl.trustStorePassword", "chimera");
            pop3Props.setProperty("mail.pop3.ssl.enable", "true");
            URLName url = new URLName("pop3", "pop.gmail.com", 995, "", username,
                    password);
            session = Session.getInstance(pop3Props, null);
            store = new POP3SSLStore(session, url);
            store.connect();
        } catch (Exception exception) {
            LOGGER.error("Not able to Connect the mail server!!");
            exception.printStackTrace();
        }
    }
    /**
     * Method to Open the Mail Folder to read and Write.
     *
     * @param folderName name of the folder to open.
     *
     * @throws Exception throws exception in
     * case not able to connect.
     */
    public void openFolder(String folderName) throws Exception {
        /*
         *  Open the Folder
         */
        folder = store.getDefaultFolder();
        folder = folder.getFolder(folderName);
        if (folder == null) {
            throw new Exception("Invalid folder");
        }
        /*
         *  try to open read/write and if that fails try read-only
         */
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
    }
    /**
     * Method to filter to get the recent and todays mails.
     *
     * @return an instance of <tt>List<EmailVO></tt>.
     *
     * @throws MessagingException
     * @throws IOException
     * @throws ParseException
     */
    public List<EmailVO> todaysDateMail() throws MessagingException,
    IOException, ParseException {
        Date sendDate = null;
        Date todaysDate = null;
        List<EmailVO> emailList = null;
        EmailVO emailVO = null;
        int recentMessage = 0;

        try {
            LOGGER.info("Folder to Scan :" + folder.getName());
            LOGGER.info("No of Msg in folder :"
                    + folder.getMessageCount());
            Message msgs[] = folder.getMessages();
            recentMessage = msgs.length;
            LOGGER.info("No of Msg in folder :" + recentMessage);
            if (recentMessage > 0) {
                emailList = new ArrayList<EmailVO>();
                for (int i = 0; i < recentMessage; i++) {
                    Message message = msgs[i];
                    /*
                     * Getting the Send Date.
                     */
                    String sdate = DateUtils.convertDateTOString(
                            message.getSentDate(), "MM/dd/yyyy");
                    sendDate = DateUtils.convertStringToDate(sdate,
                            "MM/dd/yyyy");
                    LOGGER.info("Mail Send date :" + sendDate);
                    /*
                     * Getting the Todays Date.
                     */
                    String tdate = DateUtils.convertDateTOString(new Date(),
                            "MM/dd/yyyy");
                    todaysDate = DateUtils.convertStringToDate(tdate,
                            "MM/dd/yyyy");
                    LOGGER.info("Today date :" + todaysDate);

                    // date compare between todays Date & mail sent Date.
                    if (sendDate.compareTo(todaysDate) == 0) {
                        String bcc = "";
                        Address[] address;
                        /*if ((address = message.getRecipients(Message.RecipientType.BCC)) != null) {
                            for (int j = 0; j < address.length; j++) {
                                bcc = address[j].toString();
                                LOGGER.info("BCC: " + bcc);
                            }
                        }*/
                /*    if (message.getRecipients(RecipientType.BCC) != null
                            && bcc.contains("bloomberg.interaction@gmail.com")) {*/
                        emailVO = new EmailVO();
                        /*
                         * Setting the Bcc field.
                         */
                        //emailVO.setBcc(bcc);
                        /*
                         * Setting the send Date field.
                         */
                        if (sendDate != null) {
                            LOGGER.info("Sent Date:" + sendDate);
                            emailVO.setSendDate(sendDate);
                        }
                        /*
                         * Setting the to field.
                         */
                        String to = "";
                        if ((address = message
                                .getRecipients(Message.RecipientType.TO)) != null) {
                            for (int j = 0; j < address.length; j++) {
                                 to = address[j].toString();           
                                LOGGER.info("TO: " + to);
                                EmailVO emailVOMul = new EmailVO();
                                CommonUtils.copyBeanProperties(emailVO, emailVOMul);
                                 if (CommonUtils.isValidObject(emailVOMul)) {
                                        if (to.contains("<")) {
                                            emailVOMul.setTo(to.substring(
                                                    to.indexOf("<") + 1,
                                                    to.indexOf(">")));
                                        } else {
                                            emailVOMul.setTo(to);
                                    }
                                }
                                emailList.add(getEmaiVOObject(message, emailVOMul));
                            }
                        }
                    //}
                    }// end if date compare
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return emailList;
    }
    /**
     * Method to get the Email VO Objet.
     *
     * @param message Message class.
     *
     * @param  an instance of <tt>EmailVO</tt>.
     *
     */
    private EmailVO getEmaiVOObject(Message message, EmailVO emailVO) {
        try {
            Address[] address;
            if ((address = message.getFrom()) != null) {
                for (int j = 0; j < address.length; j++) {
                    String from = address[j].toString();
                    LOGGER.info("FROM: " + from);
                    if (CommonUtils.isValidObject(emailVO)) {
                        if (from.contains("<")) {
                            emailVO.setFrom(from.substring(
                                    from.indexOf("<") + 1,
                                    from.indexOf(">")));
                        } else {
                            emailVO.setFrom(from);
                        }
                    }
                }
            }

       
        if ((address = message
        .getRecipients(Message.RecipientType.CC)) != null) {
            for (int j = 0; j < address.length; j++) {
                String cc = address[j].toString();
                LOGGER.info("CC: " + cc);
                if (CommonUtils.isValidObject(emailVO))
                    emailVO.setCc(cc);
            }
        }

        if ((message.getSubject()) != null) {
            String subject = message.getSubject();
            LOGGER.info("Subject:" + subject);
            if (CommonUtils.isValidObject(emailVO))
                emailVO.setSubject(subject);
        }

        System.out
                .println("---------------------------------");

        // Reading mail body part

        String contentType = message.getContentType();
        String textMessage = "";
        System.out.println("Message Content type:" + contentType);
        if (message.isMimeType("multipart/related")) {
            System.out.println("multipart/related".toUpperCase());
               Multipart mp = (Multipart)message.getContent(); 
             int partsCount = mp.getCount();
             for (int k = 0; k < partsCount; k++) {
                 Part p = mp.getBodyPart(k);
                 parseMail(p, emailVO);
             }
       
        }
        if (message.isMimeType("multipart/alternative")) {
            System.out.println("multipart/alternative".toUpperCase());
               Multipart mp = (Multipart)message.getContent(); 
                int partsCount = mp.getCount(); 
                for (int k = 0; k < partsCount; k++) {
                     Part p = mp.getBodyPart(k);
                     parseMail(p, emailVO);
                 }
        }
        if (contentType.contains("text/plain")
                || contentType.contains("text/html")) {
            LOGGER.info("Mail Content type is text/html!");
            textMessage = message.getContent() != null ? message
                    .getContent().toString() : "";
        } else if (contentType.contains("multipart")) {
            LOGGER.info("Mail Content type is multipart!");
            // possibly contains attachments
            Multipart multiPart = (Multipart) message
                    .getContent();
            int partCount = multiPart.getCount();
            for (int j = 0; j < partCount; j++) {
                BodyPart part = multiPart.getBodyPart(j);
                if (Part.ATTACHMENT.equalsIgnoreCase(part
                        .getDisposition())) {
                    // absolutely an attachment
                    saveAttachmentToFile(part);
                }
            }
        }
        System.out.println("Final Email body :" + emailVO.getMailBody());
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return emailVO;
    }
    public void parseMail(Part message, EmailVO emailVO)  throws Exception 
    {           
        System.out.println("parse mail Type:"+ message.getContentType());
        if ((message.isMimeType("text/*")) &&  
        (message.getDisposition() != null && message.getDisposition().equals(Part.INLINE))) 
        { 
            System.out.println("Pares mail1:" + (String)message.getContent()); 
        } else if (message.isMimeType("multipart/alternative")) { 
            Multipart mp = (Multipart)message.getContent(); 
            int partsCount = mp.getCount(); 
            for (int k = 0; k < partsCount; k++) {
                Part p = mp.getBodyPart(k);
                parseMail(p, emailVO);
            }
        } else if (message.isMimeType("multipart/related")) { 
            Multipart mp = (Multipart)message.getContent(); 
            int partsCount = mp.getCount(); 
            for (int k = 0; k < partsCount; k++) {
                Part p = mp.getBodyPart(k);
                parseMail(p, emailVO);
            }
        } else if (message.isMimeType("text/plain")) {
            LOGGER.info("Mail Content type is text/*!");
            System.out.println("Pares mail2:" + (String)message.getContent());
            emailVO.setMailBody(message.getContent().toString().replaceAll("\\<.*?>", ""));
        }
    }  
    /*
     * method use to save the attachment in mail.
     */
    private void saveAttachmentToFile(BodyPart part) throws MessagingException,
            IOException {
        String destFilePath = "/home/sougatd/mailattachments/"
                + part.getFileName();
        FileOutputStream output = new FileOutputStream(destFilePath);
        InputStream input = part.getInputStream();
        byte[] buffer = new byte[input.available()];
        int byteRead;
        while ((byteRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, byteRead);
        }
        output.close();
    }
}



/* Calling the email integration*/
EmailIntegration emailIntegration = new EmailIntegration();
          emailIntegration.setUserPass("mail@gmail.com", "password");  
         emailIntegration.connect();
            emailIntegration.openFolder("inbox");
            int totalMessages = emailIntegration.getMessageCount();
            int unreadmessage = emailIntegration.getUnreadMessageCount();
            LOGGER.info("Total messages = " + totalMessages);
            LOGGER.info("unread messages = " + unreadmessage);
            LOGGER.info("-------------------------------");
            emailVOList = emailIntegration.todaysDateMail();
            emailIntegration.closeFolder();
            emailIntegration.disconnect();

7 comments:

  1. porqueria de codigo si pierde su tiempo pongan algo que sirva

    ReplyDelete
  2. An amazing web journal I visit this blog, it's unbelievably wonderful. Oddly, in this blog's content made without a doubt and reasonable. The substance of data is informative.
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training

    ReplyDelete
  3. Thanks for sharing information and keep more updates
    Sanjary Academy provides excellent training for Piping design course. Best Piping Design Training Institute in Hyderabad, Telangana. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    Piping Design Course in India­

    ReplyDelete
  4. Nice Information
    We are the best piping design course in Hyderabad, India. Sanjary academy Offers Piping Design Course and Best Piping Design Training Institute in Hyderabad. Piping Design Institute in India Piping Design Engineering.
    Piping Design Course
    Piping Design Course in india
    Piping Design Course in hyderabad

    ReplyDelete
  5. Thanks for sharing
    "Yaaron media is one of the rapidly growing digital marketing company in Hyderabad,india.Grow your business or brand name with best online, digital marketing companies in ameerpet, Hyderabad. Our Services digitalmarketing, SEO, SEM, SMO, SMM, e-mail marketing, webdesigning & development, mobile appilcation.
    "
    Best web designing companies in Hyderabad
    Best web designing & development companies in Hyderabad
    Best web development companies in Hyderabad

    ReplyDelete
  6. Nice Post
    Best QA / QC Course in India, Hyderabad. sanjaryacademy is a well-known institute. We have offer professional Engineering Course like Piping Design Course, QA / QC Course,document Controller course,pressure Vessel Design Course, Welding Inspector Course, Quality Management Course, #Safety officer course.
    QA / QC Course
    QA / QC Course in india
    QA / QC Course in hyderabad

    ReplyDelete
  7. The Collection Marts is platform where you can view latest designs about home d├ęcor and bedding. We have large range in different categories with finest fabric in cotton and silk. You can view not only present trends but also view huge collection with reasonable price. khaadi bed sheets , cotton comforter sets , nishat linen comforter , bridal bed sheets 2018 , duvet covers The Collection Marts can provide fast service about delivery as well as customer support too. Our products are not only self-made but also, well connected with markets to ensure for possibility of available designs if client want to purchase. The Collection Marts customer support open 24/7 to guide their customers about material or product stuff.

    ReplyDelete