Using the Java Mail API in Android to Retrieve Emails from a Gmail Account

Aakash Jha
5 min readDec 29, 2022

--

The Java Mail API is a Java library that provides classes to send and receive emails through Java programs. It is a powerful tool that allows you to access your email account from within your Java code and can be particularly useful if you want to automate tasks related to email handling. In this article, we will see how to use the Java Mail API to fetch emails from a Gmail account.

Email

To use the Java Mail API, you need to have the following dependencies in your project,

Include the mail.jar, activation.jar, and additional.jar files in your Android project by following the link provided.

Mail.jar

Activation.jar

Additional.jar

To include, just paste all of them into the libs folder of your android project and right-click>add as a library.

We will use an Async task to fetch the email messages from a Gmail account in the background. This allows us to perform the task without blocking the main thread of the app, which is important for maintaining a smooth and responsive user interface.

To use an AsyncTask, we need to define a class that extends AsyncTask and overrides the doInBackground method. In the doInBackground method, we can perform the task of fetching the email messages.

private class FetchMail extends AsyncTask<String, Integer, ArrayList<String>> {


@Override
protected ArrayList<String> doInBackground(String... params) {
// fetch mail
ArrayList<String> mails = new ArrayList<String>();
String host = "pop.gmail.com";// I tried google's pop
String mailStoreType = "pop3";

String username = params[0]; //passed in through the execute() method
String password = params[1]; //passed in through the execute() method

try {
// create properties field
Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);

Store store = emailSession.getStore("pop3s");

store.connect(host, username, password);

Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);

BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));

Message[] messages = emailFolder.getMessages();

System.out.println("messages.length---" + messages.length);
for (int i = 0; i < 25; i++) {
Message message = messages[i];

System.out.println("---------------------------------");
String subjectS = message.getSubject().toString();
Object content = message.getContent();
// Get the content of the message
String body = "";

if (content instanceof String) {
// The content is a simple string, so we can return it as is
body = (String) content;
} else if (content instanceof Multipart) {
// The content is a multipart message, so we need to process each part
Multipart multipart = (Multipart) content;
// for (int j = 0; j < multipart.getCount(); j++) {
Part part = multipart.getBodyPart(0);
String contentType = part.getContentType();
if (contentType.startsWith("text/plain")) {
// This part is plain text, so we can return it as is
body = (String) part.getContent();
} else if (contentType.startsWith("text/html")) {
// This part is HTML, so we need to use an HTML parser to extract the plain text
String html = (String) part.getContent();
body = extractPlainTextFromHtml(html);
}
// }
} else if (content instanceof MimeBodyPart) {
// The content is a single MIME body part, so we can process it directly
MimeBodyPart bodyPart = (MimeBodyPart) content;
String contentType = bodyPart.getContentType();
if (contentType.startsWith("text/plain")) {
// This part is plain text, so we can return it as is
body = (String) bodyPart.getContent();
} else if (contentType.startsWith("text/html")) {
// This part is HTML, so we need to use an HTML parser to extract the plain text
String html = (String) bodyPart.getContent();
body = extractPlainTextFromHtml(html);
}
}

try {
String mailObject = String.format("{subject: \"%s\", body: \"%s\"}", subjectS, body);
mails.add(mailObject);
} catch (Exception e) {
e.printStackTrace();
}


String line = reader.readLine();
if ("YES".equals(line)) {
message.writeTo(System.out);
} else if ("QUIT".equals(line)) {
break;
}
}

emailFolder.close(false);
store.close();

} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return mails;
}

@Override
protected void onPostExecute(ArrayList<String> strings) {
super.onPostExecute(strings);
setRecyclerView(strings);

}

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
}

This code is using the JavaMail API to connect to a POP3 email server and retrieve email messages. It establishes a connection to the server using the specified host name, “pop.gmail.com”, and the specified store type, “pop3”. The username and password are passed in as parameters to the method.

The code then creates a Properties object and sets some properties that are required for connecting to a POP3 server over a secure connection using Transport Layer Security (TLS). It then creates a Session object using these properties and a Store object using the session. The Store object is used to connect to the email server using the specified host, username, and password.

Once connected, the code opens the INBOX folder in read-only mode and retrieves an array of Message objects representing the messages in the INBOX. It then iterates through the first 25 messages and extracts the subject and body of each message. If the body is in HTML format, the code calls the extractPlainTextFromHtml method to extract the plain text from the HTML. The subject and body of each message are then added to the mails ArrayList as a JSON object.

Finally, the code closes the email folder and the store.

Here is the code for extractPlainTextFromHtmlfunction:-

public static String extractPlainTextFromHtml(String html) {
StringBuilder plainText = new StringBuilder();

// Parse the HTML document
Document doc = Jsoup.parse(html);

// Extract the text from all the elements
Elements elements = doc.body().select("*");
for (Element element : elements) {
// Append the text of the element to the plain text string
plainText.append(element.text());
}

return plainText.toString();
}

This method uses the Jsoup library to parse the HTML and extract the plain text from the document body. If an exception occurs while parsing the HTML or extracting the text, it is caught and an empty string is returned.

This is just a basic example of how to use the Java Mail API to fetch emails from a Gmail account. There are many more features and options available in the API, such as the ability to send emails, work with attachments, and more.

Refer to my GitHub Repository for the whole project Code.

Thanks for reading, have a good & productive day :)

--

--