JavaMail

Introduction to JavaMail

JavaMail is a technology that provides java API to develop java based E-mail client application. It uses various protocols the send and recieve the mails but it is platform and protocol independent.

E-Mail Terminologies

Before looking into JavaMail API and it's feature we must need to familiar with few terminologies used in email application.

1. E-mail client

  • An application that is used to compose/create, read and send e-mails knows as e-mail client.

2. Mail Server

  • An application that receives e-mails from e-mail clients or from another mail server know as mail server.

  • E-mails stores at mail sever can be read, download and deleted by e-mail client.

  • Ex: Microsoft Exchange, WinGate and Microsof Windows POP3

3. Messaging System

  • An application that sends and receives e-mail from Server. Messaging system is made of many components.

  • Mail User Agent(MUA) - MAU is a client e-mail application that sends and receives messages to or from mail server. Mail User Agent sends message to Messages Transfer Agent.

  • Message Transfer Agent(MTA) - Receives messages from MUA and passes on to another MTA until it reaches to mail server. MTA stores incoming messages and delivers them to recipient. MUA and MTA clubbed together to efficiently send and receive messages to and from mail server. In case of multiple messages, it also queues them before sending. Ex: SandMail and PostFix

  • Message Delivery Agent - Stores messages into e-mail client application mailbox. As we know MTA passes/sends messages to intermediate MTA and again this is passed to next MTA, this journey continue until message reaches to final MTA. The last MTA passes messages to MDA then MDA adds it to client's mailbox or inbox.

  • Message Store - Serves as user mailbox/inbox that holds e-mails until they are read and deleted by the user.

  • SMTP - It's a protocol. It is used to send and receives e-mails over the internet.

There are the various protocols used in JavaMail API to send and receive the e-mails: SMTP, POP3, IMAP, NNTP, MIME

SMTP

Simple Message Transfer Protocol is a internet standard for e-mail transmission across IP networks. SMTP uses TCP port 25 and SMTP allows secured connections through SSL.

The com.sun.mail.smtp package

This package consist of three main classes

  1. SMTPMessage - This class is a specialization of the MimeMessage class that allows you to specify various SMTP options and parameters that will be used when this message is sent over SMTP.

  2. SMTPSSLTransport - This class implements the Transport abstract class using SMTP over SSL for message submission and transport.

  3. SMTPTransport - This class implements the Transport abstract class using SMTP for message submission and transport.

SMTP provider supports following properties which can be set into JavaMail Session object.

  • mail.smtp.host (String) - SMTP Server to connect to.

  • mail.smtp.port (String) - SMTP Server port to connect to. Default is 25.

  • mail.smtp.socketFactory.class (String) - If set, specifies the name of a class that implements the javax.net.SocketFactory interface. This class will be used to create SMTP sockets.

  • mail.smtp.socketFactory.port (int) - Specifies the port to connect to when using the specified socket factory. If not set, the default port will be used.

  • mail.smtp.auth (boolean) - If true, attempt to authenticate the user using the AUTH command. Defaults to false.

  • mail.smtp.starttls.enable (boolean) - If true, enables the use of the STARTTLS command (if supported by the server) to switch the connection to a TLS-protected connection before issuing any login commands. Defaults to false.

Example - code snippet

Properties props = new Properties();

props.put("mail.smtp.host", "smtp.gmail.com");

props.put("mail.smtp.socketFactory.port", "465");

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.port", "465");


Session session = Session.getDefaultInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(userName, password);

}

});

POP3

Post Office Protocol (POP) 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. POP supports simple download-and-delete requirements for access to remote mailboxes. A POP3 server listens on well-known port 110.

The com.sun.mail.pop3 package

  1. POP3Folder - A POP3 Folder (can only be "INBOX").

  2. POP3Message - A POP3 Message.

  3. POP3SSLStore - A POP3 Message Store using SSL.

  4. POP3Store - A POP3 Message Store.

POP3 provider supports following propertiea that can set into JavaMail Session object:

  • mail.pop3.host (String) - POP3 Server to connect to.

  • mail.pop3.port (int) - The POP3 server port to connect to, if the connect() method doesn't explicitly specify one. Defaults to 110.

  • mail.pop3.starttls.enable (boolean) - If true, requires the use of the STLS command. If the server doesn't support the STLS command, or the command fails, the connect method will fail. Defaults to false.

Example - code snippet

Properties properties = new Properties();


properties.put("mail.store.protocol", "pop3");

properties.put("mail.pop3.host", pop3Host);

properties.put("mail.pop3.port", "995");

properties.put("mail.pop3.starttls.enable", "true");


Session emailSession = Session.getDefaultInstance(properties);

JavaMail Architecture

JavaMail architecture is divided into three parts. Application layer, JavaMail API and Implementation layer. It uses various protocols to create e-mail client application.

  1. Application Layer - It uses JavaMail API to communicate with the e-mail client application.

  2. JavaMail API - Collection of classes and interfaces used to support e-mail client application functionality.

  3. Implementation Layer - Uses various protocols to transfer messages between e-mail cleant and server.

Exploring JavaMail API

Session class

The object of javax.mail.Session class used to communicate with remote systems. A session object can store information that can be shared across the e-mail client application like username, password, mail server etc. There are various properties that need to be set before creating session objects. Some of them are listed below:

  • mail.tranport.protocol (default value SMTP)

  • mail.store.protocol (default value POP3)

  • mail.host (default value Local Machine)

  • mail.user (default value is user.name)

  • mail.from (default value username@host)

  • mail.protocol.host (default value mail.host)

  • mail.protocol.user (default value mail.user)

  • mail.debug (default value False)

Session class can not be sub-classed and instantiated. It's constructor is private. There 2 static methods to get the instance of Session class. Session.getDefaultInstance(props) which return default session object that can be shared among application running in same JVM. Session.getInstance(props) return private session object. Below is the code snippet to how to get session object:

Properties properties = new Properties();

properties.put("mail.pop3.host", "pop.gmail.com");

properties.put("mail.pop3.port", "995");

properties.put("mail.pop3.starttls.enable", "true");

Session emailSession =Session.getDefaultInstance(properties);

Authenticator Class

javax.mail.Authenticator class is used to authenticate a network connection. To authenticate a user getPasswordAuthentication() method of Authentication class needs to be invoked. After creating Authentication object it must be registered with Session object so that Session object will have required authentication details to send and receive emails.

static Session getInstance(Properties props, Authenticator auth);

static Session getDefaultInstance(Properties props, Authenticator auth);

Message class

javax.mail.Message is an abstract class, used to create new email message. A mail consist of the following two components:

  1. Header - Contains information about message properties, such as subject field, recipient and sender.

  2. Content - Represents the content of the message.

MIMEMessage calss

javax.mail.internet package provides MIMEMessage class which extends Message class. MIME message accepts MIME types and headers. A MIME message can be created by creating MIMEMessage object, providing suitable attributes and content to it. There are 2 constructors, any one of them can be used to create MIMEMessage object.

public MIMEMessage(Session session) - creates empty MimeMessage by passing session object

public MimeMessage(MimeMessage msg) - creates new MimeMessage object by passing MimeMessage object

Sending E-mail

There are mainly three steps involved in sending a email over the network:

Get the Session object

    1. Set the required properties

    2. Get password authentication

// Set the required properties

Properties props = new Properties();

props.put("mail.smtp.auth", "true");

props.put("mail.smtp.starttls.enable", "true");

props.put("mail.smtp.host", "smtp.gmail.com");

props.put("mail.smtp.port", "25");


// Get the Session object on password authenticator

Session session = Session.getInstance(props,

new javax.mail.Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(userName, password);

}

});

Create default MimeMessage object and set the information

    1. Set from and to addresses

    2. Set subject of the email

    3. Set the content of the email

// Create a default MimeMessage object.

Message message = new MimeMessage(session);


// Set From: header field of the header.

message.setFrom(new InternetAddress(fromAddr));


// Set To: header field of the header.

message.setRecipients(Message.RecipientType.TO,

InternetAddress.parse(toAddr));


// Set Subject: header field

message.setSubject(subject+" - SimpleMailThruTLS");


// Now set the actual message

message.setText(text);

Send the message using Transport.send(message)

Transport.send(message);

See full code here

Receiving E-mail

There are mainly five steps involved in receiving email from specified folder.

Get the session object

create the POP3 store object and connect with the pop server

create the folder object and open it

retrieve the messages from the folder in an array and print it

close the store and folder objects