Tutorial: How to send email from a Java Application

Sending email from your java application is very straightforward when you utilize the JavaMail API.  This library contains all the functionality necessary to connect to a SMTP Mail Server and send your email to its desired recipients.  The next time you have an application performing some vital functionality instead of just logging an exception send an email to the administrator or development team so that the issue can be resolved right away.

Prerequisites

In order to use the javaMail API you need to obtain both the Java Mail and Activation Framework libraries which can be found at the following locations:

How to Send an Email

To send an email from java we must first start by importing the required classes into our MailUtil java class.

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

After we have imported the necessary resources lets go ahead with the creation of our postMail function that will send and email with subject and message, to the specified recipients, cc recipients from the sender. Also it is important to note that we will be throwing any MessagingExceptions that occur so that the caller will be responsible for handling them as they see fit.

public static void postMail( String recipients[],
    String subject, String message, String from,
    String ccRecipients[] ) throws MessagingException {

}

Now that we have our method stub in place lets begin by initializing a Mail Session configured to our SMTP Mail Server. Please note that if you utilize logging in your application you can also set the debug mode to true to get useful information.

//Create Properties
Properties props = new Properties();
props.put( "mail.smtp.host", HOST );
props.put("mail.debug", "true" );

//Get Session
Session sess = Session.getInstance(props);

After our session is initialize we can go ahead with creating our email message.

Message msg = new MimeMessage( sess );

Populate the From email address by use of the InternetAddress class

msg.setFrom(new InternetAddress(from) );

We can populate the recipents of the message utilizing the setRecipients function. This function takes two parameters the Type of recipient and the array of recipients. So we would use Message.RecipientType.TO and Message.RecipientType.CC for To and CC recipients.

// recipients
InternetAddress[] addressTo =
      new InternetAddress[recipients.length];
for( int i=0; i < recipients.length; i ++ ) {
  addressTo[i] = new InternetAddress( recipients[i] );
}
msg.setRecipients( Message.RecipientType.TO, addressTo );

// ccRecipients
if( ccRecipients != null && ccRecipients.length > 0 ) {
  InternetAddress[] addressCC =
        new InternetAddress[ccRecipients.length];
  for( int i=0; i < ccRecipients.length; i ++ ) {
    addressCC[i] = new InternetAddress( ccRecipients[i] );
  }
  msg.setRecipients( Message.RecipientType.CC, addressCC );
}

After populating the recipients of the email we can set the subject and Date of the email

msg.setSubject(subject);
msg.setSentDate(new Date() );

Finally we set the content of the email. Please note that in most cases the text format will be text/plain for simple text emails or text/html for html formatted messages.

msg.setContent( message, "text/html" );

Now that our message is prepared we send utilizing the Transport class.

Transport.send( msg);

And that is how to send an email from your Java Application, The full source for the created Utility class can be found below. If your server requires Password authentication then you may be interested in the Advanced Tutorial.

Resources

// Java //

Comments & Questions

Add Your Comment