Performance Zone is brought to you in partnership with:

I have been a programmer since I was a young child in the Gifted and Talent Program in Rutherford, NJ back in 1979. I started programming on Commodore PETs – 4 bit. And then Apple IIs, Commodore 64s and some others. Basic, then Pascal, Fortran, C, C++, Java, JavaScript and more. I am a Senior Field Engineer with Pivotal. Tim is a DZone MVB and is not an employee of DZone and has posted 59 posts at DZone. You can read more from them at their website. View Full User Profile

Sending Email With Java (Beware)

02.02.2013
| 5418 views |
  • submit to reddit

I turn on debugging to trace what’s going on. All looks good but one email bounces back after a day and some hotmail and gmails just vanish.

To test a mail server from one of our UNIX servers:

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
public class Mail {

 /// example command line run
 public static void main(String[] args) {
String sArray[] = new String[] {"tim.spann@somedomain.com", "tspann@timmail.com", "tspannjava@joemail.com"};
List<String> emails = Arrays.asList(sArray);
 Iterator<String> iterator = emails.iterator();
 while (iterator.hasNext()) {
 Mail.sendEmail("test from test", "message", iterator.next() );
}
}

/**
 * size of buffer
 */
 public static final int gkBUFFER_SIZE = 256;
/**
 * getCurrentDateTime
 * @return Date current date
 */
 public final static Date getCurrentDateTime() {
 return new Date(System.currentTimeMillis());
 }

/**
 * sendEmail
 * @param subject subject of email
 * @param message message text
 * @param emailAddress email address to send to
 * @return String log of errors/status
 */
 public final static String sendEmail(String subject, String message,
 String emailAddress) {
// email sent
 boolean emailSent = true;
// email message
 StringBuffer emailLoggingMessage =
 new StringBuffer(Mail.gkBUFFER_SIZE);
// start of message
 emailLoggingMessage
 .append("Email:")
 .append(emailAddress).append(System.getProperty("line.separator"));
// Email Properties
 Properties props = new Properties();
// add properties from properties file
 props.put("mail.smtp.host",
 "mymail.mydomain.com");
 props.put("mail.debug",
 "true");
 props.put("mail.smtp.port","25");
// -- login
 props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
 new javax.mail.Authenticator() {
 protected PasswordAuthentication getPasswordAuthentication() {
 return new PasswordAuthentication("nt domainntid", "ntpassword");
 }
 });

// / -------------
// turn on debug mode
 session.setDebug(true);
Message msg = new MimeMessage(session);
 InternetAddress addressFrom = null;
 try {
 addressFrom =
 new InternetAddress("Timothy.Spann@SomeSenderDomain.com");
 } catch (AddressException e) {
 e.printStackTrace();
emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
 try {
 msg.setFrom(addressFrom);
 } catch (MessagingException e) {
 e.printStackTrace();
emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
// recipient
 InternetAddress addressTo = null;
 try {
 addressTo = new InternetAddress(emailAddress);
 } catch (AddressException e) {
 e.printStackTrace();
 // refactor this
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
// add to address as recipient
 try {
 msg.setRecipient(Message.RecipientType.TO, addressTo);
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }

// Setting the Subject and Content Type
 try {
 msg.setSubject(subject);
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
 try {
 msg.setContent(message,"text/plain");
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
 try {
 Transport.send(msg);
 } catch (MessagingException e) {
 e.printStackTrace();
 emailLoggingMessage.append(e.getLocalizedMessage()).append(
 System.getProperty("line.separator"));
 emailSent = false;
 }
// sent message
 if (emailSent) {
 emailLoggingMessage.append("Email successfully sent.")
 .append(System.getProperty("line.separator"));
 }
// return message
 return emailLoggingMessage.toString();
 }
}

I am testing on a UNIX Server with:

– mail.sh

export ANT_OPTS="-Xms2048m -Xmx2048m -XX:MaxPermSize=1024m"
export JAVA_OPTS="-server -Xms2048m -Xmx2048m -XX:MaxPermSize=1024m"
export CLASSPATH=$CLASSPATH:dsn.jar:mail.jar:mailapi.jar:pop3.jar:smtp.jar:activation.jar:imap.jar:ojdbc14.jar:runtime12.jar:.
javac Mail.java
java Mail > mail.txt 2&> mailerr.txt

Debug Log

DEBUG: JavaMail version 1.4.4
DEBUG: URL jar:file:/home/tspann/mail/pop3.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/pop3.jar!/META-INF/javamail.providers
DEBUG: URL jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.providers
DEBUG: URL jar:file:/home/tspann/mail/imap.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/imap.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name:
{com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc],
com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc],
com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc],
com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc],
com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc],
com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]}
DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc],
imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,
com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsy stems, Inc],
smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc],
pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
DEBUG: URL jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.address.map
DEBUG: successfully loaded resource: jar:file:/home/tspann/mail/smtp.jar!/META-INF/javamail.address.map
DEBUG: setDebug: JavaMail version 1.4.4
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 "SomeSenderDomain.com", port 25, isSSL false
220 SomeSenderDomain.com SMTP Ready.
DEBUG SMTP: connected to host "SomeSenderDomain.com", port: 25

EHLO timspann.cool.com
250-ESMTP Server Ready
250-SIZE 0
250-DSN
250-STARTTLS
250 TLS
DEBUG SMTP: Found extension "SIZE", arg "0"
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "TLS", arg ""
DEBUG SMTP: use8bit false
MAIL FROM:<Timothy.Spann@SomeSenderDomain.com>
250 +OK Sender OK
RCPT TO:<tim.spann@somedomain.com>
250 +OK Recipient OK
DEBUG SMTP: Verified Addresses
DEBUG SMTP: tim.spann@somedomain.com
DATA
354 Start mail input, end with '<CR><LF>.<CR><LF>'
From: Timothy.Spann@SomeSenderDomain.com
To: tim.spann@somedomain.com
Message-ID: <117704452.0.1350396539475.JavaMail.tspann@tspann.cool.com>
Subject: test from test
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

message
.
250 +OK message queued for delivery.
QUIT
221 Service closing transmission channel closing connection

Issues with IBM AIX Websphere JDK

JavaMail API
Transport
FSQ
Javamail Summary
Javamail Docs
Javamail Docs2
Javamail Readme
SMTP Package Summary
JavaMail without a server
JavaMail

IBM Issues with SSL TLS / GMAIL

Thin Client
IBM WAS security

java.security file at /base_v61/java/jre/lib/security

Port 25
Gmail Ports
SMTP
SMTP Errors
Javamail with SMTPS/SSL
Gmail SMTP using SSL
Javamail to Hotmail
SSL – Android
STARTTTLS
Javamail from Websphere
Sending Gmail
SSL Error Certificate
IBM Support
IBM Support
IBM Support

Javamail with TLS on AIX

SSL

Published at DZone with permission of Tim Spann, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Lund Wolfe replied on Sat, 2013/02/02 - 3:30am

If you are just sending email, the apache commons email is short and easy and reliable with gmail and hotmail.  Attachments and image embeds are easy, too.

You still have to download emails the hard way with JavaMail.

John J. Franey replied on Sat, 2013/02/02 - 10:39am

What is your expectation regarding email delivery?  Is it understood that it is not reliable?  No client implementation, pick your favorite implementation language, can overcome this nature of email delivery. 

Configure your client to connect to a local email relay, one that runs on your localhost or lan.  Use a local email relay that successfully receives email from your java client.  Faults in connecting to remote servers are more aptly handled by the local mail relay.   Don't rely on the java client to provide store and retry.  Take advantage of delivery techniques provided by your dependable mail-relay implementation.   There are many tools and much experience at that level.  There are many mail-relay implementations available on unix servers.  On some distributions, it is already configured and running, or easy to install and setup.


Tim Spann replied on Sat, 2013/02/02 - 12:18pm

 Ours was dying on hotmail and gmail only.  Turned out to be a mail server issue with one particular email address used for sending.  Black list security issue.



  /**
    *
    * @param subject
    * @param message
    * @param emailAddress
    * @return
    */
   public final static String sendEmail(String subject, String message, String emailAddress) {
     // email sent
     boolean emailSent = false;

     // email message
     StringBuilder emailLoggingMessage =
         new StringBuilder(UserProvisioningUtility.gkBUFFER_SIZE);

     // start of message
     emailLoggingMessage
         .append(Messages.getString("UserProvisioningProcess.SMTP_MESSAGE_LOG"))
         .append(emailAddress).append(System.getProperty("line.separator"));
     
     Email email = new SimpleEmail();
     //email.setHostName("smtp.googlemail.com");
     //email.setSmtpPort(465);
     email.setHostName(Messages.getString("UserProvisioningProcess.EMAIL_SERVER"));
     
     int smtpPort = 25;
     if ( null != Messages.getString("UserProvisioningProcess.EMAIL_PORT")) {
       try {
         smtpPort = Integer.parseInt(Messages.getString("UserProvisioningProcess.EMAIL_PORT"));
       }
       catch(Throwable t) {
         emailLoggingMessage.append(t.getLocalizedMessage()).append(
             System.getProperty("line.separator"));         
       }
     }
     email.setSmtpPort(smtpPort);
     
//     email.setAuthenticator(new DefaultAuthenticator("username", "password"));
//     email.setSSLOnConnect(true);
     try {
       email.setFrom(Messages.getString("UserProvisioningProcess.FROM_EMAIL"));
     } catch (EmailException e) {
       emailLoggingMessage.append(e.getLocalizedMessage()).append(
           System.getProperty("line.separator"));
     }
     email.setSubject(subject);
     try {
       email.setMsg(message);
     } catch (EmailException e) {
       emailLoggingMessage.append(e.getLocalizedMessage()).append(
           System.getProperty("line.separator"));
     }
     try {
       email.addTo(emailAddress);
     } catch (EmailException e) {
       emailLoggingMessage.append(e.getLocalizedMessage()).append(
           System.getProperty("line.separator"));
     }
     try {
       email.send();
       emailSent = true;
     } catch (EmailException e) {
       emailLoggingMessage.append(e.getLocalizedMessage()).append(
           System.getProperty("line.separator"));
     }
     
     // sent message
     if (emailSent) {
       emailLoggingMessage.append(
           Messages.getString("UserProvisioningProcess.SMTP_MESSAGE_SENT"))
           .append(System.getProperty("line.separator"));
     }
     
     return emailLoggingMessage.toString();
   }

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.