Send email using Java Program
Last Updated :
14 Sep, 2023
Sending Email is a basic requirement regardless of which platform you are working on like JAVA, JavaEE, Python etc. Sending Email may be required to send error alerts or confirmation of registration or signup. Java provides the facility to send emails by writing java programs.
To send emails using Java, you need three things:
- JavaMail API
- Java Activation Framework (JAF)
- Your SMTP server details
You may download the latest version of both JavaMail API and JAF from the official website of Java. After successfully downloading these two, extract them. Add mail.jar , smtp.jar and activation.jar file in your classpath to be eligible to send emails.
After adding these files, follow the below steps and write a java program to send email:
- Create a new session object by calling getDefaultInstance() method and passing properties as argument to get all of the important properties like hostname of the SMTP server etc.
Create a MimeMessage object by passing the session object created in previous step.
- The final step is to send email using the javax.mail.Transport
Java
// Java program to send email
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "[email protected]";
// email ID of Sender.
String sender = "[email protected]";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// set body of the email.
message.setText("This is a test mail");
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
Output:
Mail successfully sent
Sending Email to Multiple Recipients
Sending Email to multiple recipients is same as that for single recipient. The difference is that to send a mail to multiple recipients you should add multiple recipients. To add multiple recipients we have to invoke the following method and pass the type of recipient and list of email addresses as arguments:
void addRecipients(Message.RecipientType type, Address[] addresses)
throws MessagingException
{
}
For adding Email in 'TO' field, you may use Message.RecipientType.To . Similarly for adding Email in 'CC' and 'BCC' fields, you will have to use Message.RecipientType.CC and Message.RecipientType.BCC.
The argument addresses in the above method is an array containing the list of all Email-IDs. You will have to use the InternetAddress() method for specifying Emails.
Suppose you want to send email to 4 persons. You have to create a string array of size 4 and store the email addresses of the recipients in it. Follow the above program for sending a simple email and instead of adding a single recipient, add multiple recipients using the addRecipients method as shown below:
Java
// create a new String array
String[] recipients = new String[4];
// add email addresses
recipients[0] = first@gmail.com
recipients[1] = second@gmail.com
recipients[2] = third@gmail.com
recipients[3] = fourth@gmail.com
// inside of try block instead of using addRecipient()
// use addRecipients()
// specify the type of field(TO, CC ,BCC)
// pass the array of email ids of recipients
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Sending Emails with HTML template
Some times emails are send with an HTML template i.e., the body of the Email is written in HTML. This makes the email well formatted and attractive in appearance. The program to send email with a HTML template is almost same as that of sending normal emails. The difference is, we have to use setContent() method instead of setText() method for specifying the body of the email and in the method setContent() we have to specify the second argument as "text/html" and first argument will be HTML code. Let us now have a look at the program to send email with HTML templates:
Java
// Java program to send email
// with HTML templates
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "[email protected]";
// email ID of Sender.
String sender = "[email protected]";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// set body of the email.
message.setContent("<h1>This is a HTML text</h1>","text/html");
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
Output:
Mail successfully sent
Sending Email With Attachments
The JavaMail API allows you to send emails containing attachments. To send email with attachments we have to create two MimeBodyPart objects and assign the text to one object and datahandler to other. The process of sending emails with attachments is described in brief below:
- Create a new session object
- Create a MimeBodyPart object and assign text to it
- Create a new MimeBodyPart object and assign DataHandler object to it
- Create a MultiPart object and assign the two MimeBodyPart objects to this MultiPart Object
- Set this MultiPart object to message.SetContent() method.
- use Transport() method to send the mail
Let us now look at the program to do this:
CPP
// Java program to send email
// with attachments
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class SendEmail
{
public static void main(String [] args)
{
// email ID of Recipient.
String recipient = "[email protected]";
// email ID of Sender.
String sender = "[email protected]";
// using host as localhost
String host = "127.0.0.1";
// Getting system properties
Properties properties = System.getProperties();
// Setting up mail server
properties.setProperty("mail.smtp.host", host);
// creating session object to get properties
Session session = Session.getDefaultInstance(properties);
try
{
// MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From Field: adding senders email to from field.
message.setFrom(new InternetAddress(sender));
// Set To Field: adding recipient's email to from field.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
// Set Subject: subject of the email
message.setSubject("This is Subject");
// creating first MimeBodyPart object
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is body of the mail");
// creating second MimeBodyPart object
BodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "attachment.txt"
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// creating MultiPart object
Multipart multipartObject = new MimeMultipart();
multipartObject.addBodyPart(messageBodyPart1);
multipartObject.addBodyPart(messageBodyPart2);
// set body of the email.
message.setContent(multipartObject);
// Send email.
Transport.send(message);
System.out.println("Mail successfully sent");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
Output:
Mail successfully sent
Note: Here we have used the localhost SMTP server for sending emails. If you want to use any email sending client like Gmail, Yahoo etc then you will have to use respective SMTP server host addresses.
Similar Reads
Java Programming Basics
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming console
4 min read
Java Hello World Program
Java is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat
6 min read
Socket Programming in Java
Socket programming in Java allows different programs to communicate with each other over a network, whether they are running on the same machine or different ones. This article describes a very basic one-way Client and Server setup, where a Client connects, sends messages to the server and the serve
6 min read
How to Run Java Program?
Java is a popular, high-level, object-oriented programming language that was developed by James Gosling and his team at Sun Microsystems (now owned by Oracle Corporation) in the mid-1990s. It is widely used for developing various kinds of software, including web applications, desktop applications, m
2 min read
Communication Between two Programs using JSON
JSON stands for JavaScript Object Notation. To communicate between computer and human we use a programming language. To communicate between two programs, there must be a common data format and here we use JSON format. Let us say you have an application with Frontend written in Python and Backend wri
3 min read
Download Web Page using Java
Downloading a webpage can be helpful in many situations, such as downloading different web pages locally, data scraping or building our own tool. We can automate this process using a Java program. In this article, we are going to learn how to download a web page using Java with Java's I/O and networ
2 min read
Sending Message to Kafka Using Java
Apache Kafka is an open-source real-time data handling platform. It is used to transmit messages between two microservices. The sender is referred to as the Producer, who produces the messages, and the receiver is referred to as the Consumer, who consumes the messages. In this setup, Kafka acts as a
4 min read
Java SE vs Java EE
Java is a highly popular and versatile programming language used globally to create various applications. Two major Java platforms are Java SE (Standard Edition) and Java EE (Enterprise Edition). Understanding the differences between these platforms is crucial for developers working on enterprise-le
5 min read
JRF Event Streaming in Java
Event streaming is a powerful tool for developers that allows them to process and react to data in real-time. This is possible in the Java programming language by utilizing the Java Remote Function (JRF) framework. This article will go over how to use JRF event streaming in Java, as well as the vari
4 min read
Java String getBytes() Method
In Java, the getBytes() method of the String class converts a string into an array of bytes. This method is useful for encoding the strings into binary format, which can then be used for file I/O, network transmission, or encryption. It can be used with the default character set or with a specified
2 min read