Home > Android > SMTP & IMAP Using SSL in Java Android

SMTP & IMAP Using SSL in Java Android


1 – IMAP: Internet Access Message Protocol – is an Application Layer Internet protocol that allows an e-mail client to access e-mail on a remote mail server.

It is a new protocol that is upgraded from POP (Post Office Protocol – is an application-layer Internet standard protocol used by local e-mail clients to retrieve e-mail from a remote server over a TCP/IP connection).
IMAP supports: on-line & off-line and disconnected modes of operation:
-In On-line mode: Users can access and work with their messages while they still keep the connection to server. All emails will exist on server until users delete them.
-In Off-line mode: It works like POP, All messages are sent to client from server and then they are deleted on server and the connection is closed. User can connect to server again when sending message.
-In Disconnected mode: Users can save their message on client and work with them and then update their message to server in the next connection.

POP & IMAP Working Flow

2 – IMAPS – IMAP using SSL.
SSL: Secure Sockets Layer, is a general-purpose or multi-purpose protocol which designed to create communication between two application programs on a specified port (socket 443) to encrypt all sent and received information. Nowaday it is used for electronic information transactions such as transfer credit card numbers, passwords, secret personal number (PIN) on the Internet.
SSL was designed and first developed in 1994 by the research team lead by Netscape & Elgammal and today has become the standard security practices on the Internet. SSL version 3.0 is still being edited and improved. The below image is a sample “How do SSL work”.

The algorithm of encryption and authentication using SSL is included (version 3.0):
DES – Data encryption standard (born 1977), invented and used by the U.S. government
DSA – digital signature algorithm, standard electronic identity, invented and used by the U.S. government
Planning – key exchange algorithm, invented and used by the U.S. government
MD5 – algorithms create value “hash (message digest), invented by Rivest;
RC2, RC4 – Rivest encryption, developed by RSA Data Security Company;
RSA – public key algorithm for encryption and authentication, developed by Rivest, Shamir and Adleman;
RSA key exchange – key exchange algorithm for SSL based on RSA algorithm;
SHA-1 – secure hash algorithm, developed and used by U.S. government
Skipjack – symmetric key algorithm classification is done in hardware Fortezza, used by U.S. government
Triple-DES – DES encryption three times.

Secure sockets layer (SSL) protocol, the dominant mode for secure browser-server communications. (Image courtesy of MIT OCW)

3 – Some sample code to connect and get all mails on Gmail in java as below:
-Step 1: Download JavaMail , an external library from SUN on http://java.sun.com/products/javamail/downloads/index.html
-Step 2: Import JavaMail by Eclipse

-Step 3: Import some packages form JavaMail in code

import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

-Step 4: Create a properties for session:
Properties props = new Properties();
//IMAPS protocol
props.setProperty(“mail.store.protocol”, “imaps”);
//Set host address
props.setProperty(“mail.imaps.host”, imaps.gmail.com);
//Set specified port
props.setProperty(“mail.imaps.port”, “993”);
//Using SSL
props.setProperty(“mail.imaps.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
props.setProperty(“mail.imaps.socketFactory.fallback”, “false”);
//Setting IMAP session
Session imapSession = Session.getInstance(props);
-Step 5: Get all mails by IMAPS
Store store = imapSession.getStore(“imaps”);
//Connect to server by sending username and password.
//Example mailServer = imap.gmail.com, username = abc, password = abc

store.connect(mailServer, account.username, account.password);
//Get all mails in Inbox Forlder

inbox = store.getFolder(“Inbox”);
//Return result to array of message

Message[] result = inbox.getMessages();
1 – Simple Mail Transfer Protocol (SMTP) is an Internet Standard for e-mail transmission across Internet Protocol networks. SMTPS – SMTP using SSL

2 – Some sample code to connect and send email on Gmail in java as below:
-Step 1: Still import JavaMail library as Step 1, 2, 3 in IMAP
-Step 2: Create a class Email Authentication as below:

package com.glandore.fda.utils.email;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class EmailAuthenticator extends Authenticator    {
private EmailAccount account;
public EmailAuthenticator(EmailAccount account) {
this.account = account;
//Override getPasswordAuthentication to transfer emailAddress and password to get an authentication.

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account.emailAddress, account.password);

// Email account class to contain email information.

package com.glandore.fda.utils.email;
public class EmailAccount {
public String urlServer = “gmail.com”;
public String username = “namheo”;
public String password = “xxxxx”;
public String emailAddress;
public EmailAccount(String username, String password, String urlServer) {
this.username = username;
this.password = password;
this.urlServer = urlServer;
this.emailAddress = username + “@” + urlServer;

-Step 3: Create a properties for session:

//Create an authetication email
EmailAuthenticator authenticator = new EmailAuthenticator(account);
//Create a property for smtp sesion

Properties props = new Properties();
//Setting smtps protocol

props.setProperty(“mail.transport.protocol”, “smtps”);
//Setting stmpHost. Example: smtpHost = smtp.gmail.com

props.setProperty(“mail.host”, stmpHost);
//Setting specified port

props.put(“mail.smtp.port”, “465”);
props.put(“mail.smtp.socketFactory.port”, “465”);
//Setting using SSL

props.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
props.put(“mail.smtp.socketFactory.fallback”, “false”);
props.setProperty(“mail.smtp.quitwait”, “false”);
//Enable authentication

props.put(“mail.smtp.auth”, “true”);
//Setting smtp session
smtpSession = Session.getDefaultInstance(props, authenticator);

-Step 4: Create a ByteArrayDataSource class to convert the body of message to bytes.

package com.glandore.fda.utils.email;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataSource;
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
this.data = data;
this.type = type;
public ByteArrayDataSource(byte[] data) {
this.data = data;
public void setType(String type) {
this.type = type;
public String getContentType() {
if (type == null)
return “application/octet-stream”;
return type;
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
public String getName() {
return “ByteArrayDataSource”;
public OutputStream getOutputStream() throws IOException {
throw new IOException(“Not Supported”);

-Step 5: Send email

//Example: sender=nam.tran.flash@gmail.com recipients = nam.tran@glandoresystems.com
//body= the body of message, subject= the title of message
MimeMessage message = new MimeMessage(smtpSession);
//Create handler data to contain the body of message in bytes using ByteArrayDataSource

DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), “text/plain”));
//Put information in message

message.setSender(new InternetAddress(sender));

if (recipients.indexOf(‘,’) > 0)
//Check recipients to send many email address at the same time
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
//Send email

Please check the source code here http://www.box.net/shared/k2vzvynl7x


Categories: Android Tags: , , , ,
  1. mag
    16/11/2010 at 6:50 am

    how can I run this program?

  2. Mike
    19/11/2010 at 10:14 pm

    Wonderful! =)

  3. Ronil
    16/03/2011 at 6:26 pm

    i tried this code, its compiling however its not running on the emulator at all. Can you tell me where I am going wrong or missing something ?
    Thanks 🙂

  4. John
    25/05/2012 at 2:15 pm

    Great example

  5. himura
    12/08/2012 at 10:36 pm

    Just a quick question
    So in the sample code in this page, IMAP was used to read an email while STMP was used to send an email. forgive my background limitations, is it always this way? STMP for sending emails and IMAP for retrieving them?

  6. Troll
    04/09/2012 at 10:04 am

    This is not always this way. Actually, Imap (Internet Message Access Protocol) and POP3(Post Office Protocol) are protocols to retrieve messages, from a mailbox. Smtp(Simple Mail Transfer Protocol) is another protocol but this one can only send an email to a server.
    Basically, if you want to read an email, you use Imap or Pop3, and to send one you use SMTP.
    Others protocols are existing (Exchange by example), but I don’t know much about it.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: