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.
Before looking into JavaMail API and it's feature we must need to familiar with few terminologies used in email application.
An application that is used to compose/create, read and send e-mails knows as e-mail client.
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
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
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.
This package consist of three main classes
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.
SMTPSSLTransport - This class implements the Transport abstract class using SMTP over SSL for message submission and transport.
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.
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);
}
});
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.
POP3Folder - A POP3 Folder (can only be "INBOX").
POP3Message - A POP3 Message.
POP3SSLStore - A POP3 Message Store using SSL.
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.
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 is divided into three parts. Application layer, JavaMail API and Implementation layer. It uses various protocols to create e-mail client application.
Application Layer - It uses JavaMail API to communicate with the e-mail client application.
JavaMail API - Collection of classes and interfaces used to support e-mail client application functionality.
Implementation Layer - Uses various protocols to transfer messages between e-mail cleant and server.
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);
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);
javax.mail.Message is an abstract class, used to create new email message. A mail consist of the following two components:
Header - Contains information about message properties, such as subject field, recipient and sender.
Content - Represents the content of the message.
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
There are mainly three steps involved in sending a email over the network:
Set the required properties
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);
}
});
Set from and to addresses
Set subject of the email
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);
Transport.send(message);
See full code here
There are mainly five steps involved in receiving email from specified folder.