Over a million developers have joined DZone.

Java Mail API On Android Working with a Restful API on the Web

· Java Zone

Discover how powerful static code analysis and ergonomic design make development not only productive but also an enjoyable experience, brought to you in partnership with JetBrains

Java Mail API On Android

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

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.java – GMail Email Sender using JavaMail

package com.ourimlementation.java.androidmail;

import java.io.UnsupportedEncodingException;
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 = "smtp.gmail.com";

	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);
			emailMessage.addRecipient(Message.RecipientType.TO,
					new InternetAddress(toEmail));
		}

		emailMessage.setSubject(emailSubject);
		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());
		transport.close();
		Log.i("GMail", "Email sent successfully.");
	}
}

SendMailActivity.java – Android Activity to Compose and Send Email

package com.ourimlementation.java.androidmail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
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;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_send_mail);
		initializeWidgets();
	}
	
	private void initializeWidgets()
	{
		buttonSend = (Button) this.findViewById(R.id.button1);
		senderEmail = (TextView) this.findViewById(R.id.editText1);
		senderPassword = (TextView) this.findViewById(R.id.editText2);
		recipientEmail = (TextView) this.findViewById(R.id.editText3);
		emailSubject = (TextView) this.findViewById(R.id.editText4);
		emailBody = (TextView) this.findViewById(R.id.editText5);
		recipientEmailList = new ArrayList<String>();
		buttonSend.setOnClickListener(this);
	}
	
	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();
	}

	@Override
	public void onClick(View v)
	{
		// TODO Auto-generated method stub
		switch(v.getId())
		{
		case R.id.button1:
			getValues();
			new SendMailTask(SendMailActivity.this).execute(strSenderEmail, strSenderPassword, recipientEmailList, strEmailSubject, strEmailBody);
			break;
		}
	}
}

SendMailTask.java – Android AsyncTask for Sending Email

package com.ourimlementation.java.androidmail;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
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...");
		statusDialog.setIndeterminate(false);
		statusDialog.setCancelable(false);
		statusDialog.show();
	}

	@Override
	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(),
					args[4].toString());
			publishProgress("Preparing mail message....");
			androidEmail.createEmailMessage();
			publishProgress("Sending email....");
			androidEmail.sendEmail();
			publishProgress("Email Sent.");
			Log.i("SendMailTask", "Mail Sent.");
		} catch (Exception e) {
			publishProgress(e.getMessage());
			Log.e("SendMailTask", e.getMessage(), e);
		}
		return null;
	}

	@Override
	public void onProgressUpdate(Object... values) {
		statusDialog.setMessage(values[0].toString());
	}

	@Override
	public void onPostExecute(Object result) {
		statusDialog.dismiss();
	}
}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>




Learn more about Kotlin, a new programming language designed to solve problems that software developers face every day brought to you in partnership with JetBrains.

Topics:

Published at DZone with permission of Andrey Prikaznov, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}