JavaMail quick start

Home arrow Java Tutorials arrow Java Essentials arrow JavaMail quick start
JavaMail quick start Print E-mail
Contributed by Joe   
Wednesday, 21 June 2006

JavaMail API Abstract

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform.
News of JavaMail API

JavaMail API 1.4 Release

The JavaMail 1.4 release includes many API improvements approved by the Java Community Process via JSR-919. It also includes improvements in MIME parsing performance and support for parsing and constructing Delivery Status Notifications. Note: You will also need the JavaBeans Activation Framework (JAF) extension that provides the javax.activation package. We suggest you use version 1.1 of JAF, the latest release.


Reviewing JavaMail related protocols

The Simple Mail Transfer Protocol (SMTP) is defined by RFC 821. It defines the mechanism for delivery of e-mail. In the context of the JavaMail API, your JavaMail-based program will communicate with your company or Internet Service Provider's (ISP's) SMTP server. That SMTP server will relay the message on to the SMTP server of the recipient(s) to eventually be acquired by the user(s) through POP or IMAP. This does not require your SMTP server to be an open relay, as authentication is supported, but it is your responsibility to ensure the SMTP server is configured properly. There is nothing in the JavaMail API for tasks like configuring a server to relay messages or to add and remove e-mail accounts.


POP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939 defines this protocol.


IMAP is a more advanced protocol for receiving messages. Defined in RFC 2060, IMAP stands for Internet Message Access Protocol, also known as IMAP4. When using IMAP, your mail server must support the protocol. You can't just change your program to use IMAP instead of POP and expect everything in IMAP to be supported. Assuming your mail server supports IMAP, your JavaMail-based program can take advantage of users having multiple folders on the server and these folders can be shared by multiple users.


MIME stands for Multipurpose Internet Mail Extensions. It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822, RFC 2045, RFC 2046, and RFC 2047.

Fundamentals of the JavaMail API 

The Session class defines a basic mail session. It is through this session that everything else works. The Session object takes advantage of a java.util.Properties object to get information like mail server, username, password, and other information that can be shared across your entire application.

The constructors for the class are private. You can get a single default session that can be shared with the getDefaultInstance() method:

Properties props = new Properties();
// fill props with any information
Session session = Session.getDefaultInstance(props, null);


Or, you can create a unique session with getInstance():

Properties props = new Properties();
// fill props with any information
Session session = Session.getDefaultInstance(props, null);


Once you have your Session object, it is time to move on to creating the message to send. This is done with a type of Message. Because Message is an abstract class, you must work with a subclass, in most cases javax.mail.internet.MimeMessage. A MimeMessage is an e-mail message that understands MIME types and headers, as defined in the different RFCs. Message headers are restricted to US-ASCII characters only, though non-ASCII characters can be encoded in certain header fields.

To create a Message, pass along the Session object to the MimeMessage constructor:

MimeMessage message = new MimeMessage(session);


Once you've created the Session and the Message, as well as filled the message with content, it is time to address your letter with an Address. Like Message, Address is an abstract class. You use the javax.mail.internet.InternetAddress class.

To create an address with just the e-mail address, pass the e-mail address to the constructor:

Address address = new InternetAddress(" ");

If your message needs to show multiple from addresses, use the addFrom() method:

Address address[] = ...;




An example of sending email with JavaMail API

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail {
    public static void send(String smtpHost, int smtpPort,
                            String from, String to,
                            String subject, String content)
                throws AddressException, MessagingException {

        // Create a mail session
        java.util.Properties props = new java.util.Properties();
        props.put("", smtpHost);
        props.put("mail.smtp.port", ""+smtpPort);
        Session session = Session.getDefaultInstance(props, null);
        // Construct the message
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        // Send the message
    public static void main(String[] args) throws Exception {
        // Send a test message
        send("hostname", 25, "
", " ",
             "Hello", "Hello, \n\n How are you ?");

 If SMTP server requires AUTH,just add below code

Properties props = System.getProperties();
props.put("", host);
    // Setup mail server
    Authenticator auth = new MyAuthenticator();
Session session = Session.getDefaultInstance(props, auth);

Receive email via POP3

    * "receive" method to fetch messages and process them.
  public static void receive(String popServer, String popUser
   , String popPassword)
  { Store store=null;
    Folder folder=null;

      // -- Get hold of the default session --
      Properties props = System.getProperties();
      Session session = Session.getDefaultInstance(props, null);

      // -- Get hold of a POP3 message store, and connect to it --
      store = session.getStore("pop3");
      store.connect(popServer, popUser, popPassword);
      // -- Try to get hold of the default folder --
      folder = store.getDefaultFolder();
      if (folder == null) throw new Exception("No default folder");

      // -- ...and its INBOX --
      folder = folder.getFolder("INBOX");
      if (folder == null) throw new Exception("No POP3 INBOX");

      // -- Open the folder for read only --;

      // -- Get the message wrappers and process them --
      Message[] msgs = folder.getMessages();
      for (int msgNum = 0; msgNum < msgs.length; msgNum++)

    catch (Exception ex)
      // -- Close down nicely --
        if (folder!=null) folder.close(false);
        if (store!=null) store.close();
      catch (Exception ex2) {ex2.printStackTrace();}



Last Updated ( Saturday, 01 July 2006 )

  home              contact us


©2006-2014   All rights reserved     powered by Mambo Designed by Siteground