Jun 122012
 

POP & IMAP are the protocols used to receive emails. What is the difference between between the two?

Solution:

Before getting into the differences, lets learn few terminologies used commonly:

email client v/s webmail

Both webmail and email clients are applications for sending and receiving email, and they use similar methods for doing this.

Webmail is an application written to be used over the internet (through web browser), usually with no downloaded applications or additional software necessary. All the work of sending / receiving emails, etc is done by the remote server. For example: GMail, Yahoomail, rediffmail, hotmail etc.

So if I am sending an email thru yahoomail, I am telling the remote server to send the email, and the remote sever is sending the email on my behalf. what we see in the bowser is just an interface.

email client is an application installed on your system. This application interact with the remote server to perform the task of sending / receiving emails. Since its a desktop application, some of the backend work can also be performed by it (along with all the front end work of enabling to write mails etc). Microsoft Outlook, Windows Live mail, Mozila thunderbird etc are email clients.

Many webmails also provide users ability to configure their email clients to talk to the server of webmail and send/receive emails (thus by-passing the need for webclient). For example, you can configure your Outlook to use your GMail account.

POP (Post Office Protocol)

In the earlier times, when email users used to have only one machine to access the email and limited bandwidth. System used to download all the emails from the server to the local machine. email clients like Microsoft Outlook used to work in the fashion. they download all the emails from the server to the client and delete them from server.

So If I have downloaded email to one client, I cannot access the mail from other machine (because the email is no more at the server). The protocol which receive emails like this is POP (Post Office Protocol).

Note that GMail, etc cannot work using POP, because it allows users to read email from anywhere all the time.

POP3 is the current version of this protocol, and remains to be one of the most popular protocol to receive emails.

IMAP (Internet Message Access Protocol)

IMAP seems to be more suitable to the modern day email usage, where users want to read emails from multiple machines and want the access to them always.

IMAP does not delete the email from the server until the user delete them, hence a user can access same email from multiple clients many a times.

Because emails are always on the server, it may take a major chunk of the memory at server, but gone are the days when memory used to be an issue. Still some email clients provide facility to keep archive of emails on your local system.

This page shows the entire list of protocols used in email.

  One Response to “Difference between POP & IMAP”

Comments (1)
  1. JavaMail is a Java API used to receive (via POP3/IMAP) and send email (via SMTP). JavaMail can also be used to build mail client for Android.
    You need to import following three jar in the project :
    mail-1.4.5.jar
    activation.jar
    additionnal.jar

    Mail server has different way of identifying each mail as unique. They set unique ID – mailId to identify it, but all mail servers does not support uniqueId mechanism. If the sending mail server does not set the mail Id, and if you download the mail from the receiving server, then you wont get the mailId in the downloaded mail. I am now explaining the mail server structure as well as the unique mechanism used generally (term “generally” is used because if you build your own mail server and decide not to set the id or anything else while sending it then its ur own choice, GOD BLESS ALL).
    Most of the mail server (like Gmail, Yahoo, etc) are folder-structured. For eg: INBOX,SENT,SPAM,DELETE etc. Each folder has its own unique Id and name. It has uid associated with it, which keeps on incrementing as the new mail goes to that folder.
    For eg:
    Lets say we create a folder with name folderX. UID = 0.
    As mail is inserted into it, UID=1. UID for that mail = 1.
    This mail is deleted from it -> the mail goes to DELETE folder. UID(folderX) – not affected. UID for this mail will be again set according to the DELETE folder.
    Another mail is inserted in folderX -> UID=2.
    When a mail is inserted in that particular folder, the uid is incremented by one and goes on increasing. Simple 🙂

    1. Download Mail through IMAP:

    /** Initializing connection
    * There is something wrong with MailCap,
    * javamail can not find a handler for the multipart/mixed part,
    * so this bit needs to be added.
    */
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    mc.addMailcap(“text/html;; x-java-content-handler=com.sun.mail.handlers.text_html”);
    mc.addMailcap(“text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml”);
    mc.addMailcap(“text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain”);
    mc.addMailcap(“multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed”);
    mc.addMailcap(“message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822”);
    CommandMap.setDefaultCommandMap(mc);

    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true);
    Properties props = new Properties();
    props.put(“mail.imap.ssl.enable”, “true”);
    props.put(“mail.imap.ssl.socketFactory”, sf);
    Session imapSession = Session.getInstance(props, null);

    Store store = imapSession.getStore(“imap”);
    //config for gmail
    store.connect(“imap.gmail.com”, 993, “xyz@gmail.com”, “abc”);

    //getting all folders
    Folder[] folders = store.getDefaultFolder().list(“*”);
    for (int i=0;i<folders.length;i++) {
    Folder folder = folders[i];
    if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
    // msgCount = folder.getDeletedMessageCount()!=-1?folder.getMessageCount()-folder.getDeletedMessageCount():folder.getMessageCount();
    //folder name = folder.getFullName();
    }
    }

    //getting latest 20mails headers for ~ folderName:"INBOX" , mailHeaderCount:0 , numberOfMails:20
    IMAPFolder imapFolder = (IMAPFolder) store.getFolder("INBOX");
    imapFolder.open(Folder.READ_ONLY);
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);
    int totalMessages = folderName.toUpperCase().contains(DBConstants.KEY_TRASH)? imapFolder.getMessageCount() : imapFolder.getMessageCount() – imapFolder.getDeletedMessageCount();
    int end = (totalMessages – mailHeaderCount) <= 0 ? 0 : (totalMessages – mailHeaderCount);
    int start = (end – numberOfMails) <= 0 ? 1 : (end – numberOfMails);
    if(end != 0){
    Message[] inboxMsgs = imapFolder.getMessages(start , end);
    imapFolder.fetch(inboxMsgs, fp);
    int size = inboxMsgs.length;
    for (int j = 0; j < size; j++){
    IMAPMessage message = (IMAPMessage) inboxMsgs[size-j-1];
    // msgId = message.getMessageID();
    // sentDate = message.getSentDate();
    // receivedDate = message.getReceivedDate();
    // Address[] from = message.getFrom();
    // Address[] to = message.getRecipients(RecipientType.TO);
    // Address[] cc = message.getRecipients(RecipientType.CC);
    // Address[] bcc = message.getRecipients(RecipientType.BCC);
    // subject = message.getSubject();
    // isSeen = message.isSet(Flags.Flag.SEEN);
    // uid = imapFolder.getUID(message);
    }
    }
    imapFolder.close(false); //false to let no modification changes to occur

    //getting mail content for~ uid:15, folderName:"INBOX"
    IMAPFolder imapFolder = (IMAPFolder) store.getFolder(folderName);
    imapFolder.open(Folder.READ_WRITE);
    //READ_WRITE will change the status of the mail as SEEN
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.CONTENT_INFO);
    Message[] inboxMsgs = imapFolder.getMessagesByUID(new long[]{uid});
    imapFolder.fetch(inboxMsgs, fp);
    IMAPMessage message = (IMAPMessage) inboxMsgs[0];
    // msgID = message.getMessageID();
    // contentType = message.getContentType();
    // size = message.getSize();
    // getTextFromObject(message);
    imapFolder.close(true); // true to set mail as SEEN if you want

    private boolean textIsHtml=false;
    private String text="";
    private String html="";
    private void getTextFromObject(Part m) throws IOException, MessagingException
    {
    Object o = m.getContent();
    if (o instanceof String) {
    String s = getText(m);
    if(textIsHtml)
    html+=s;
    else
    text+=s;
    textIsHtml = false;
    }else if (o instanceof Multipart) {
    Multipart mp = (Multipart)o;
    int count3 = mp.getCount();
    Log.d(LOG_TAG,"It has " + count3 +" BodyParts in it**");
    for (int j = 0; j < count3; j++) {
    // Part are numbered starting at 0
    BodyPart bp = mp.getBodyPart(j);
    String mimeType = bp.getContentType();
    Log.d(LOG_TAG,, "BodyPart " + (j+1) +" is of MimeType " + mimeType);
    Object o2 = bp.getContent();
    if (o2 instanceof String) {
    Log.d(LOG_TAG,,"**This is a String BodyPart**");
    String s = getText(bp);
    if(textIsHtml)
    html+=s;
    else
    text+=s;
    textIsHtml = false;
    }else {
    Log.d(LOG_TAG,,"**This BodyPart is a nested Multipart or Inputstream. Handle accordingly.");
    getTextFromObject(bp);
    }
    }
    }else if (o instanceof InputStream) {
    //System.out.println("**This is an InputStream message**");
    //write code to get inputstream.
    if(m.getFileName()!=null){
    String id="";
    Enumeration headers = m.getAllHeaders();
    while(headers.hasMoreElements())
    {
    Header h = (Header) headers.nextElement();
    if(h.getName().equalsIgnoreCase(DBConstants.KEY_ATTACHMENT_ID)){
    id = h.getValue();
    }
    }

    Attachment attachment = new Attachment();
    attachment.setId(id);
    attachment.setName(m.getFileName());
    attachment.setSize(m.getSize());
    attachments.add(attachment);
    }

    }
    }

    2. Sending Mail through SMTP
    /** Initializing connection
    * There is something wrong with MailCap,
    * javamail can not find a handler for the multipart/mixed part,
    * so this bit needs to be added.
    */
    MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
    mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
    mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
    mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
    mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
    CommandMap.setDefaultCommandMap(mc);

    Properties propSMTP = new Properties();
    propSMTP.put("mail.smtp.host", "smtp.gmail.com");
    propSMTP.put("mail.smtp.socketFactory.port", "465");
    propSMTP.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    propSMTP.put("mail.smtp.auth", "true");
    propSMTP.put("mail.smtp.port", "465");

    smtpSession = Session.getInstance(propSMTP,
    new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication("xyz@gmail.com","abc");
    }
    });

    Session smtpSession.setDebug(true); //you can set debug to true to see logs while sending mail
    MimeMessage message = new MimeMessage(smtpSession);
    message.setSender(new InternetAddress("xyz@gmail.com"));
    message.setSubject(subject);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientTO));
    message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(recipientCC));
    message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(recipientBCC));
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(body,"text/html");
    // Set html message part
    multipart.addBodyPart(messageBodyPart);
    // Put parts in message
    message.setContent(multipart);
    Transport.send(message);

    That's it. You have build yourself a mail client. You can add various features support such as ATTACHMENT,FORWARDING,REPLYING,SEARCH,etc by using javaMail.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)