Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Sending Emails in Java with JavaMail API

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. It is an optional package (standard extension) for reading, composing, and sending electronic messages.

JavaMail provides elements that are used to construct an interface to a messaging system. JavaMail includes several classes that implement RFC822 and MIME Internet messaging standards. These classes are delivered as part of the JavaMail class package.

Protocols Supported by JavaMail API:

Protocol Description
SMTP Acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver email.
POP Acronym for Post Office Protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. RFC 1939 defines this protocol.
IMAP Acronym for Internet Message Access Protocol. It is an advanced protocol for receiving messages. It provides support for multiple mailbox for each user, in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.
MIME Acronym 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. As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs.
NNTP and Others There are many protocols that are provided by third-party providers. Some of them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.

JavaMail API Architecture

Following is an architecture the JavaMail API follows:

JavaMail Architecture

Figure 1: JavaMail Architecture

As can be seen in the above diagram, a JavaBean is used to interact with you mail box through JavaMail API. Protocols like SMTP/POP/IMAP help to achieve this. As these protocols have implementation to access the mailbox and JavaMail API acts as interface between user and mailbox.

Installation and Setup

To start using JavaMail API you need to first download and set it up as explained below:

  • You can download latest version of from Java's standard website.
  • You would also need JAF- Java Activation Framework. You can download latest version of from Java's standard website.

Download and decompress these files. Now add mail.jar and activation.jar files in your CLASSPATH.

mail.jar contains Java classes for JavaMail API

activation.jar contains classes for Java Activation Framework. These classes are required for JavaMail API to run.

JavaMail API Core Classes

JavaMail API consists of some classes that are used to send, read, fetch, and delete email messages. Let us summarize these classes:

Session Class

  • Represents a mail session
  • Uses Properties to get things like mail host
    • mail.host
    • mail.smtp.host
  • Get session - no constructor
    • Session session = Session.getInstance(props, null); // null for Authenticator
    • Session session = Session.getDefaultInstance(props, null);

Message Class

  • Represents a mail message
    • Message abstract class
    • implements Part
    • MimeMessage is MIME style email message
    • implements MimePart
  • Get message from session
    • MimeMessage message = new MimeMessage(session);
  • Set parts
    • message.setContent() / mimeMessage.setText()

InternetAddress Class

  • RFC822 Address
  • Create
    • new InternetAddress("somename@somedomain.com");
    • new InternetAddress(" somename@somedomain.com ", "FirstName LastName");
  • For To, From, CC, BCC
    • message.setFrom(address)
    • message.addRecipient(type, address)
    • Types
    • Message.RecipientType.TO
    • Message.RecipientType.CC
    • Message.RecipientType.BCC

Authenticator Class

  • Permit mechanism to prompt for username and password
    • javax.mail.Authenticator != java.net.Authenticator
  • Extend Authenticator
  • Override
	public PasswordAuthentication getPasswordAuthentication() { 
  	 String username, password; // Then get them ... 
   	return new PasswordAuthentication(username, password); 
	}

Transport Class

  • Message transport mechanism
  • Get transport for session
    • Transport transport = session.getTransport("smtp");
  • Connect
    • transport.connect(host, username, password);
  • Act - repeat if necessary
    • transport.sendMessage(message, message.getAllRecipients());
  • Done
    • transport.close();
  • Store and Folder

    • Used to get messages.
    • Connect to Store :
    • // Store store = session.getStore("imap");
      Store store = session.getStore("pop3");
      store.connect(host, username, password); 
    • After connecting to Store, connect to Folder to read messages from it:
    • Folder folder = store.getFolder("INBOX"); 
      	folder.open(Folder.READ_ONLY); 
      	Message message[] = folder.getMessages(); 
    • Once you have a Message to read, you can get its content with getContent() or write its content to a stream with writeTo(). The getContent() method only gets the message content, while writeTo() output includes headers.
    • Once done close Folder and Store.
      • folder.close(aBoolean);
    • store.close();
      • The boolean passed to the close() method of folder states whether or not to update the folder by removing deleted messages.

    Now that you have a basic idea of JavaMail API and its core classes let us understand how to send, fetch and delete messages in the following section:

    Send Email Messages

    Following types of email can be sent using JavaMail API:

    • Simple email
    • Email with attachments
    • Email with inline image
    • Email with HTML content

    For all these cases we follow following basic steps:

    We first need a working SMTP server:

    1. Get a session
    2. Create a default MimeMessage object and set From, To, Subject in the message.
    3. Set actual message using the code below:
    4. message.setText(“your actual message goes here”);
      
    5. Send the message using the Transport object.
    	String host = ...;
    	String from = ...;
    	String to = ...;
    
    	// Get system properties
    	Properties props = System.getProperties();
    
    	// Setup mail server
    	props.put("mail.smtp.host", host);
    
    	// Get session
    	Session session = Session.getDefaultInstance(props, null);
    
    	// Define message
    	MimeMessage message = new MimeMessage(session);
    	message.setFrom(new InternetAddress(from));
    	message.addRecipient(Message.RecipientType.TO, 
     	 new InternetAddress(to));
    	message.setSubject("Hello JavaMail");
    	message.setText("Welcome to JavaMail");
    
    	// Send message
    	Transport.send(message);
    

    Fetching Email Messages

    For fetching email messages, following basic steps needs to be followed:

    • Get a Session
    • Create pop3 Store object and connect with pop server.
    • Create folder object. Open the appropriate folder in your mailbox.
    • Get your messages.
    • Close the Store and Folder objects.
    String host = ...;
    String username = ...;
    String password = ...;
    
    // Create empty properties
    Properties props = new Properties();
    
    // Get session
    Session session = Session.getDefaultInstance(props, null);
    
    // Get the store
    Store store = session.getStore("pop3");
    store.connect(host, username, password);
    
    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);
    
    // Get directory
    Message message[] = folder.getMessages();
    
    for (int i=0, n=message.length; i<n; i++) {
       System.out.println(i + ": " + message[i].getFrom()[0] 
         + "\t" + message[i].getSubject());
    }
    
    // Close connection 
    folder.close(false);
    store.close();
    

    Deleting Messages

    Deleting email messages using JavaMail API means changing Flags associated with messages. Following is the list of the flags associated with any message:

    • Flags.Flag.ANSWERED
    • Flags.Flag.DELETED
    • Flags.Flag.DRAFT
    • Flags.Flag.FLAGGED
    • Flags.Flag.RECENT
    • Flags.Flag.SEEN
    • Flags.Flag.USER

    To delete a message following basic steps needs to be followed:

    • Get the Session object with POP and SMPT server details in the properties.
    • Create POP3 store object and connect to the store. Create Folder object and open the appropriate folder in your mailbox in READ_WRITE mode.
    • Retrieves messages from inbox folder.
    • Iterate through the messages, delete the message by invoking the method setFlag(Flags.Flag.DELETED, true) on the Message object.
    • The messages marked DELETED are not actually deleted, until we call the expunge() method on the Folder object, or close the folder with expunge set to true.
    • Then, when you are done processing all messages, close the folder, passing in a true value to expunge the deleted messages.: folder.close(true);

    Conclusion:

    In this article we saw an overview of the JavaMail API. Steps to be followed to send,retrieve and delete email messages. Hope you liked the article.



    Web developer and passioned for web design, SEO and front end technologies.

    What did you think of this post?
    Services
    [Close]
    To have full access to this post (or download the associated files) you must have MrBool Credits.

      See the prices for this post in Mr.Bool Credits System below:

    Individually – in this case the price for this post is US$ 0,00 (Buy it now)
    in this case you will buy only this video by paying the full price with no discount.

    Package of 10 credits - in this case the price for this post is US$ 0,00
    This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

    Package of 50 credits – in this case the price for this post is US$ 0,00
    This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


    > More info about MrBool Credits
    [Close]
    You must be logged to download.

    Click here to login