DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Sending Email With Java (Beware)

Sending Email With Java (Beware)

Tim Spann user avatar by
Tim Spann
CORE ·
Feb. 02, 13 · Interview
Like (1)
Save
Tweet
Share
8.75K Views

Join the DZone community and get the full member experience.

Join For Free

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

JavaMail Java (programming language)

Published at DZone with permission of Tim Spann, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Tech Layoffs [Comic]
  • API Design Patterns Review
  • Asynchronous HTTP Requests With RxJava
  • Top 5 PHP REST API Frameworks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: