Now I have created a code to retrieve unread email and read its body and then we can store or do whatever we want to do.
It is completely working but the problem is that it giving me only the body for the first mail and for the second it gives the body with html tags.
I'm using JavaMail API...
How can I do??
Thanks in advance.
Best regards, Ali
package pack1;
//import the necessary classes
import java.io.IOException;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public class InboxReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "mail", "pass");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
//Message messages[] = inbox.getMessages();
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[] = inbox.search(ft);
int i =0;
for(Message message:messages)
{
Multipart mp = (Multipart)messages[i].getContent();
Object p = mp.getBodyPart(i).getContent();
String q = p.toString();//object has the body content
System.out.println(q);//prints the body
System.out.println( messages[i].getSubject()+ " \n"+i);i++;
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The output :
a
a
0
<div dir="ltr">b<br>
</div>
b
1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at javax.mail.Multipart.getBodyPart(Multipart.java:156)
at javax.mail.internet.MimeMultipart.getBodyPart(MimeMultipart.java:258)
at pack1.InboxReader.main(InboxReader.java:39)