Javamail Example - Send Mail in Java Using SMTP
Javamail Example - Send Mail in Java Using SMTP
Today we will learn how to use JavaMail API to send emails using SMTP server with no authentication, TLS and SSL
authentication and how to send attachments and attach and use images in the email body. For TLS and SSL
authentication, I am using GMail SMTP server because it supports both of them.
JavaMail API is not part of standard JDK, so you will have to download it from it’s official website i.e JavaMail Home
Page. Download the latest version of the JavaMail reference implementation and include it in your project build path.
The jar file name will be javax.mail.jar.
If you are using Maven based project, just add below dependency in your project.
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
1. Creating javax.mail.Session object
The logic to create session differs based on the type of SMTP server, for example if SMTP server doesn’t require any
authentication we can create the Session object with some simple properties whereas if it requires TLS or SSL
authentication, then logic to create will differ.
So I will create a utility class with some utility methods to send emails and then I will use this utility method with
different SMTP servers.
Our EmailUtil class that has a single method to send email looks like below, it requires javax.mail.Session and some other
required fields as arguments. To keep it simple, some of the arguments are hard coded but you can extend this method
to pass them or read it from some config files.
package com.journaldev.mail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
package com.journaldev.mail;
import java.util.Properties;
import javax.mail.Session;
public class SimpleEmail {
The program is simple to understand and works well, but in real life most of the SMTP servers use some sort of
authentication such as TLS or SSL authentication. So we will now see how to create Session object for these
authentication protocols.
package com.journaldev.mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
*/
public static void main(String[] args) {
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
}
}
Since I am using GMail SMTP server that is accessible to all, you can set the correct variables in above program and run
for yourself. Believe me it works!! 🙂
package com.journaldev.mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for SSL: 465
*/
public static void main(String[] args) {
final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id
final String password = "mypassword"; // correct password for gmail id
final String toEmail = "myemail@yahoo.com"; // can be any email id
System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
The program is almost same as TLS authentication, just some properties are different. As you can see that I am calling
some other methods from EmailUtil class to send attachment and image in email but I haven’t defined them yet.
Actually I kept them to show later and keep it simple at start of the tutorial.
/**
* Utility method to send email with attachment
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendAttachmentEmail(Session session, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with attachment!!");
}catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
The program might look complex at first look but it’s simple, just create a body part for text message and another body
part for attachment and then add them to the multipart. You can extend this method to attach multiple files too.
Since we can create HTML body message, if the image file is located at some server location we can use img element to
show them in the message. But sometimes we want to attach the image in the email and then use it in the email body
itself. You must have seen so many emails that have image attachments and are also used in the email message.
The trick is to attach the image file like any other attachment and then set the Content-ID header for image file and then
use the same content id in the email message body with <img src='cid:image_id'>.
/**
* Utility method to send image in email body
* @param session
* @param toEmail
* @param subject
* @param body
*/
public static void sendImageEmail(Session session, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with image!!");
}catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
If your program is stuck in Transport send() method call, check that SMTP port is correct. If it’s correct then use telnet to
verify that it’s accessible from you machine, you will get output like below.
That’s all for JavaMail example to send mail in java using SMTP server with different authentication protocols,
attachment and images. I hope it will solve all your needs for sending emails in java programs.