Sending Email using the Javamail Package

It's easy to send mail from your Java app using the standard Javamail package. For the most basic case (no authentication) the code is short and simple. Unfortunately the situation changes if you need authentication. This is largely because different mail servers do things in slightly different ways.

The code below was tested in February of 2013 with Javamail 1.4.5 talking over SSL to a Sendmail daemon listening to port 465. It works. On the other hand there are many good reasons why the code below might not work with your mail server. If you have trouble sending emails using Javamail you might want to:

Test Code

You will find below a simple test app. Email addresses and host names are all dummy values - you will, of course, need to use your information:

import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.*;

public class test_mail
{
   public static void main(String[] args) throws AddressException, MessagingException 
   {
      final boolean use_auth = true,
                     use_ssl = true,
                     use_tls = false;
         
      final String      from = "\"Testing\" < test [at] azertech.net > ",
                       recip = "\"recipient\" < test [at] azertech.net > ",
                        host = "smtp dot azertech dot net",
                        user = "test",
                        pass = "test",
                   ssl_trust = "*";
         
      final int         port = 465,
                     timeout = 30;

      final String   subject = "This is a test",
                        body = "Testing";
         
      Properties props = System.getProperties();
      props.put("mail.smtp.host", host );
      props.put("mail.smtp.port", String.valueOf(port) );
            
      if ( use_auth )
      {
         props.put( "mail.smtp.auth",               "true" );
         props.put( "mail.smtp.user",               user );
         props.put( "mail.smtp.password",           pass );
               
         props.put( "mail.smtp.starttls.enable",    use_tls ? "true" : "false" );
         props.put( "mail.smtp.ssl.enable",         use_ssl ? "true" : "false" );
         props.put( "mail.smtp.connectiontimeout",  timeout * 1000 );
         props.put( "mail.smtp.timeout",            timeout * 1000 );
         props.put( "mail.smtp.ssl.trust",          ssl_trust );
      }

      Session session = Session.getInstance( props, 
                           new Authenticator() 
                           {
                              protected PasswordAuthentication getPasswordAuthentication() 
                              {
                                 return new PasswordAuthentication( user, pass );
                              }
                           });
            
      session.setDebug(true);
            
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(recip));
      message.addRecipient(Message.RecipientType.CC, new InternetAddress(recip));
      message.addRecipient(Message.RecipientType.BCC, new InternetAddress(recip));
      message.setSubject( subject );
      message.setText( body );

      Transport.send(message);
   }
}

Debug Output

When I ran the above code against a sendmail server (using SSL, port 465) I got the following output (slightly edited:)


DEBUG: setDebug: JavaMail version 1.4.5
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp [at] azertech [dot] net", port 465, isSSL true
220 smtp [at] azertech [dot] net ESMTP Sendmail 8.14.3/8.14.3/Debian-9.1ubuntu1; Sat, 16 Feb 2013 14:05:34 -0500; (No UCE/UBE) logging access from: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz(OK)-zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz [zzzzzzzzzzzzzzzz]
DEBUG SMTP: connected to host "smtp [at] azertech [dot] net", port: 465

EHLO dev [dot] azertech [dot] net
250-smtp [at] azertech [dot] net Hello zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz [zzzzzzzzzzzzzzz], pleased to meet you
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-EXPN
250-VERB
250-8BITMIME
250-SIZE
250-DSN
250-ETRN
250-AUTH DIGEST-MD5 CRAM-MD5 LOGIN PLAIN
250-DELIVERBY
250 HELP
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "EXPN", arg ""
DEBUG SMTP: Found extension "VERB", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "SIZE", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ETRN", arg ""
DEBUG SMTP: Found extension "AUTH", arg "DIGEST-MD5 CRAM-MD5 LOGIN PLAIN"
DEBUG SMTP: Found extension "DELIVERBY", arg ""
DEBUG SMTP: Found extension "HELP", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM 
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:
250 2.1.0 ... Sender ok
RCPT TO:
250 2.1.5 ... Recipient ok
RCPT TO:
250 2.1.5 ... Recipient ok
RCPT TO:
250 2.1.5 ... Recipient ok
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   recipient 
DEBUG SMTP:   recipient 
DEBUG SMTP:   recipient 
DATA
354 Enter mail, end with "." on a line by itself
From: Testing 
To: recipient 
Cc: recipient 
Message-ID: <1119455398.0.1361041528780.JavaMail.test [at] dev [dot] azertech [dot] net>
Subject: This is a test
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Testing
.
250 2.0.0 r1GJ5Yju006348 Message accepted for delivery
QUIT
221 2.0.0 smtp [at] azertech [dot] net closing connection

Tags: