Java Mail API On Android working With A Restful API On The...

Java Mail API On Android working With A Restful API On The Web

0 36155
Java Mail API On Android

Java Mail API On Android working With A Restful API On The Web

The JavaMail API is considered a bona fide set of classes for building a fully functional mail system that remains unconstrained by any protocols or platform. Now, the APIs serve an even greater goal when they are used for the RESTful API web services. But that comes later.

Let’s take a more insightful look into Java Mail API and understand why it is on the rise:

While giving you the wherewithal of creating avant-garde interfaces, Java Mail API can spruce up some basic applications by integrating the electronic mail feature with them.

There is a myriad of requirements it addresses in its own unique way:

  • The developer-friendliness is achieved by a design that is liner yet effective.
  • The programming concepts used here are not alien to those who know their way around Java APIs, for example, the error handling feature is not much different, and so isn’t the JDK 1.1 event-handling programming models.
  • You can add formidably powerful and versatile mail-based applications which have the wherewithal to handle the intricate mail message formats as well.

There is a very apparent influence of technologies like IMAP and MAPI in Java Mail API but as opposed to those technologies, you have an easier time using it because they don’t have the luxury of integrating the straightforward Java programming language concepts.

The Architecture


Java Mail has a layered architecture that is characterized by a bunch of attributes:

  • It has the abstract layer that dictates the rules for user interface, classes and other functions that contribute in efficient mail handling.
  • Then you have the Internet implementation layer that leverages the internet standards – RFC822 and MIME for implementing abstract layer components.
  • Also, the JavaBeans Activation Framework (JAF) comes to play when encapsulation of the message data has to be performed. It also proves to be resourceful when you need to manage some commands that will facilitate interaction with data files.

Insight into REST

Now, the Representational State Transfer (REST) is a highly followed architecture that is comprised by several clients and servers. It helps the clients to either fetch or to modify a resource state and it gets a response from the server which sends across the desired representation of the resource. When we talk of resource, we usually refer to the object’s properties. You can take an object to be a user who has certain attributes like name, location, position, etc. There can also be a unique numeric identification for the user. And this resource then can be further represented by the REST API through something like JSON, XML, Binary, etc.

Making REST Callouts in Android

While there are different ways to do so, one of the most fuss free way happens to be the one where we leverage a design pattern created by Virgil Dobjanschi. Via that pattern, the developer of the app in question makes use of the services, the intents (note that APIs also use intents) and the database in order to support the data state that is being processed in the app.

REST Callouts

It is the RESTMethod that defines the HTTP URL and HTTP request body. It then goes on to implement the HTTP transaction before processing the HTTP response. Now, there is a chance that this process takes more time than required, and thus, it is recommended that you run it in the Worker thread. And instead of the JAVA URL connection, you are advised to use the Apache HTTP client for building in Android.

In order to evaluate or find out the current state of the resource, all an application has to do is to query the database with a set of data that is new and updated with the latest entries.

Let us take an example of how the complete process is carried out with a piece of code – GMail Email Sender using JavaMail

import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import android.util.Log;
public class GMail {
        final String emailPort = "587";// gmail's smtp port
        final String smtpAuth = "true";
        final String starttls = "true";
        final String emailHost = "";
        String fromEmail;
        String fromPassword;
        List toEmailList;
        String emailSubject;
        String emailBody;
        Properties emailProperties;
        Session mailSession;
        MimeMessage emailMessage;
        public GMail() {
        public GMail(String fromEmail, String fromPassword,
                        List toEmailList, String emailSubject, String emailBody) {
                this.fromEmail = fromEmail;
                this.fromPassword = fromPassword;
                this.toEmailList = toEmailList;
                this.emailSubject = emailSubject;
                this.emailBody = emailBody;
                emailProperties = System.getProperties();
                emailProperties.put("mail.smtp.port", emailPort);
                emailProperties.put("mail.smtp.auth", smtpAuth);
                emailProperties.put("mail.smtp.starttls.enable", starttls);
                Log.i("GMail", "Mail server properties set.");
        public MimeMessage createEmailMessage() throws AddressException,
                        MessagingException, UnsupportedEncodingException {
                mailSession = Session.getDefaultInstance(emailProperties, null);
                emailMessage = new MimeMessage(mailSession);
                emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
                for (String toEmail : toEmailList) {
                        Log.i("GMail","toEmail: "+toEmail);
                                        new InternetAddress(toEmail));
                emailMessage.setContent(emailBody, "text/html");// for a html email
                // emailMessage.setText(emailBody);// for a text email
                Log.i("GMail", "Email Message created.");
                return emailMessage;
        public void sendEmail() throws AddressException, MessagingException {
                Transport transport = mailSession.getTransport("smtp");
                transport.connect(emailHost, fromEmail, fromPassword);
                Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients());
                transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
                Log.i("GMail", "Email sent successfully.");
} – Android Activity to Compose and Send Email

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SendMailActivity extends Activity implements OnClickListener
        private Button buttonSend;
        private TextView senderEmail, senderPassword, recipientEmail, emailSubject, emailBody;
        private List<String> recipientEmailList;
        private String strSenderEmail, strSenderPassword, strRecipientEmail, strEmailSubject, strEmailBody;
        public void onCreate(Bundle savedInstanceState) {
        private void initializeWidgets()
                buttonSend = (Button) this.findViewById(;
                senderEmail = (TextView) this.findViewById(;
                senderPassword = (TextView) this.findViewById(;
                recipientEmail = (TextView) this.findViewById(;
                emailSubject = (TextView) this.findViewById(;
                emailBody = (TextView) this.findViewById(;
                recipientEmailList = new ArrayList<String>();
        private void getValues()
                strSenderEmail = senderEmail.getText().toString();
                strSenderPassword = senderPassword.getText().toString();
                strRecipientEmail = recipientEmail.getText().toString();
                recipientEmailList = Arrays.asList(strRecipientEmail.split("\\s*,\\s*"));
                strEmailSubject = emailSubject.getText().toString();
                strEmailBody = emailBody.getText().toString();
        public void onClick(View v)
                // TODO Auto-generated method stub
                        new SendMailTask(SendMailActivity.this).execute(strSenderEmail, strSenderPassword, recipientEmailList, strEmailSubject, strEmailBody);
} – Android AsyncTask for Sending Email

import java.util.List;
import android.os.AsyncTask;
import android.util.Log;
public class SendMailTask extends AsyncTask {
        private ProgressDialog statusDialog;
        private Activity sendMailActivity;
        public SendMailTask(Activity activity) {
                sendMailActivity = activity;
        protected void onPreExecute() {
                statusDialog = new ProgressDialog(sendMailActivity);
                statusDialog.setMessage("Getting ready...");
        protected Object doInBackground(Object... args) {
                try {
                        Log.i("SendMailTask", "About to instantiate GMail...");
                        publishProgress("Processing input....");
                        GMail androidEmail = new GMail(args[0].toString(),
                                        args[1].toString(), (List) args[2], args[3].toString(),
                        publishProgress("Preparing mail message....");
                        publishProgress("Sending email....");
                        publishProgress("Email Sent.");
                        Log.i("SendMailTask", "Mail Sent.");
                } catch (Exception e) {
                        Log.e("SendMailTask", e.getMessage(), e);
                return null;
        public void onProgressUpdate(Object... values) {
        public void onPostExecute(Object result) {


<uses-permission android:name="android.permission.INTERNET"/>
Author Bio: Lucie Kruger is a technology associate with a great expertise in Java and is associated with a leading company Mobiers Ltd. In-case you are looking forward to avail the services of Android apps development company, then feel free to contact her for best advices.



Leave a Reply