wellnwill

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

 
Footer with Map