How to send email using Javamail with Exchange

Last updated on 12th February 2016

In this article I will explain how to send emails from a Java program using Javamail API. The sample program in this article demonstrates how to make an authenticated SMTP connection with TLS(Transport Layer Security) enabled.

Javamail API is an open source platform independent framework to send and receive emails. You can download the latest Javamail release from this link here

Program Logic

The program starts by defining a set of properties(key value pairs) that are essential for making a connection to the Exchange server. These properties are explained in the following table

mail.smtp.hostSMTP server to connect
mail.smtp.portPort number on the SMTP server to connect
mail.smtp.starttls.enableSet to true will enable TLS protected connection
mail.smtp.ssl.trustSet to the SMTP server name to trust the server without checking the server certificate.
mail.smtp.connectiontimeoutConnection timeout in milliseconds

The program then creates a mail session using the above properties along with username and password for authentication.

Next step is to create a MIME style email message object and set the various parameters such as From address, To address, message subject and message body.

Finally, the connect() and sendMessage() methods of the transport class is used to send the message to the recipients.

Program Source

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.PasswordAuthentication;


public class SendMail {
   public static void main(String[] args){
	
      try {

	Properties props =  new Properties();
	props.put("mail.smtp.host", "mysmtp.server.com");
	props.put("mail.smtp.port", "587");
	props.put("mail.smtp.ssl.trust", "mysmtp.server.com");
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.connectiontimeout", "10000");

	final String EmailUser = "EmailAccountName";
	final String EmailPassword = "EmailAccountPassword";

	Session session = Session.getInstance(props, new javax.mail.Authenticator() {
			  protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(
					EmailUser,EmailPassword);
			     }
		   });

	session.setDebug(true);	
	InternetAddress fromAddress = new InternetAddress("hilary@server.com",
							"Hilary Clinton");
	InternetAddress toAddress = new InternetAddress("donald@server.com",
							"Donald Trump");
	String msgSubject = "Top Secret";
	String msgBody = "This email send from a Java program. \n" +
			"Check out www.opentechguides.com for the source code";

	Message msg = new MimeMessage(session);
	msg.setFrom(fromAddress);
	msg.addRecipient(Message.RecipientType.TO,toAddress);
	msg.setSubject(msgSubject);
	msg.setText(msgBody);

	Transport transport = session.getTransport("smtp");
	transport.connect();
	transport.sendMessage(msg, msg.getAllRecipients());
	   
   }
   catch (MessagingException e) {
	System.out.println(e.getMessage()+ e.getStackTrace());
   }
   catch (UnsupportedEncodingException e) {
	System.out.println(e.getMessage());
   }
 }
}

Post a comment

Comments

Sanjeev Kumar | July 24, 2022 6:53 AM |

Thank you so much for posting this sample program in precise manner. It helped me a lot and saved me from sleepless nights.

Asad | July 14, 2017 10:06 AM |

DEBUG SMTP: need username and password for authentication i'm getting this error

Jimmy | June 17, 2016 7:03 AM |

Thanks So much. This solved it