Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

10.16. Sending Mail with SMTP

10.16.1. Problem

You need to send an email.

10.16.2. Solution

Use SMTPClient from Commons Net. The following example sends a simple email to somedude@aol.org from tobrien@discursive.com via the SMTP server on host www.discursive.com using port 25:

import org.apache.commons.net.smtp.SMTPClient;
SMTPClient client = new SMTPClient( );
client.connect("www.discursive.com");
client.sendSimpleMessage("tobrien@discursive.com", 
                         "somedude@aol.com", 
                         "Hey! Call me when you get a chance." );
client.disconnect( );

This example sends a very simple email message to one recipient by passing three arguments to client.sendSimpleMessage() : the sender's email address, the recipient's email address, and a message. If you are trying to send a simple email message to multiple recipients, pass a String[] containing each address as the second parameter to sendSimpleMessage( ). The following example sends a simple email message to multiple recipients by passing a String[] to sendSimpleMessage( ):

import org.apache.commons.net.smtp.SMTPClient;
SMTPClient client = new SMTPClient( );
client.connect("www.discursive.com");
String[] recipients = new String[2];
recipients[0] = "mission-control@nasa.gov";
recipients[1] = "announce@nasa.gov";
client.sendSimpleMessage("astronaut@nasa.gov", 
                         recipients, 
                         "The eagle has landed." );
client.disconnect( );

10.16.3. Discussion

Telnet to port 25 of a SMTP server, and you will see the server respond with a numeric code (220). SMTPReply.isPositiveCompletion( ) returns true if the response code of the previously executed command is between 200 and 299; the value of the initial response code, 220, is equal to the public static variable SMTPReply.SERVICE_READY. The following example uses getReplyCode( ) and SMTPReply.isPositiveCompletion() to test the connection to the SMTP server:

import org.apache.commons.net.smtp.SMTP;
import org.apache.commons.net.smtp.SMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
SMTPClient client = new SMTPClient( );
client.connect("www.discursive.com");
int response = client.getReplyCode( );
if( SMTPReply.isPositiveCompletion( response ) ) {
    // Set the sender and the recipients
    client.setSender( "tobrien@discursive.com" );
    client.addRecipient( "president@whitehouse.gov" );
    client.addRecipient( "vicepresident@whitehouse.gov" );
    // Supply the message via a Writer
    Writer message = client.sendMessageData( );
    message.write( "Spend more money on energy research.  Thanks." );
    message.close( );
    // Send the message and print a confirmation
    boolean success = client.completePendingCommand( );
    if( success ) {
        System.out.println( "Message sent" );                
    }
} else {
    System.out.println( "Error communicating with SMTP server" );
}
client.disconnect( );

Instead of sendSimpleMessage( ), the previous example sets a sender address and two recipient addresses using setSender( ) and addRecipient(). The message body is then written to a Writer returned by sendMessageData(). When the Writer is closed, the message is sent by calling completePendingCommand(). completePendingCommand( ) returns true if the message has been queued for delivery.

10.16.4. See Also

JavaMail is the set of utilities contained in the javax.mail package, and JavaMail is usually used in conjunction with the Java Activation Framework (JAF) to send email messages using SMTP. Commons Net does not aim to replace the JavaMail API, but it does provide a very straightforward alternative for sending email messages. For more information about JavaMail, see the JavaMail product page at http://java.sun.com/products/javamail. For more information about the JavaMail API, see Chapter 10, "JavaMail Best Practices," in Java Enterprise Best Practices (O'Reilly).


Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.