Send email using Java Program

31 Aug, 2021
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 = "recipient@gmail.com";       // email ID of  Sender.      String sender = "sender@gmail.com";       // 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 arrayString[] recipients = new String[4]; // add email addressesrecipients[0] = first@gmail.comrecipients[1] = second@gmail.comrecipients[2] = third@gmail.comrecipients[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 recipientsmessage.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 = "recipient@gmail.com";       // email ID of  Sender.      String sender = "sender@gmail.com";       // 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 = "recipient@gmail.com";             // email ID of Sender.        String sender = "sender@gmail.com";             // 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.This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
rs1686740
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Introduction to Java
Initialize an ArrayList in Java