Friday, 10 January 2014

Read Email in Java - Android

The easiest way to read email in Java

If you need to read email from Java app you will need mail library. Most famous library for reading email in java is javax.mail.jar and you can find it on this link. That work fine in simple Java app, but if you want to build Android app to read email you will have a big problem. 

There is a problem with mail.jar when you want to build Android app, some classes in mail.jar don't work and when you deploy your android app on phone you will get some error but code is fine. In order to solve that problem you need to use this jar files: activation.jar, additionnal.jar and mail.jar. Javax mail.jar include activation and additional jars but some classes in that jars aren't working in Android so you must download files from this link.

First you say what protocol you gonna use:
Properties props = new Properties();
props.setProperty("", "imaps");

Then you open a connection to your server:
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("", "", "password");

Open inbox with read_write mode:
Folder inbox = store.getFolder("INBOX");;

If you want you can see how much message you have in inbox:

Get message:
Message msg = inbox.getMessage(inbox.getMessageCount());
Write all address:
Address[] in = msg.getFrom();
for (Address address : in) {
    System.out.println("FROM:" + address.toString());
Write content of message on console:
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());

You need to put all that in try block and the code will work from simple Java app to Android app.
If you have any questions or need help with coding post a comment bellow.
And if you like this post please share it. Have a good one.

No comments:

Post a Comment