Comments on: Difference between POP & IMAP https://demo.ritambhara.in/difference-between-pop-imap/ Coding / System Design Interviews Fri, 08 Mar 2013 05:03:48 +0000 hourly 1 https://wordpress.org/?v=6.7.2 By: akash https://demo.ritambhara.in/difference-between-pop-imap/#comment-1714 Fri, 08 Mar 2013 05:03:48 +0000 http://www.ritambhara.in/?p=297#comment-1714 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.

]]>