Java Sending Email

Java programming language allows its users to send emails using the program. This process is called Java Sending Email. Java provides  JavaMail API to facilitate email sending process. There are various methods to send emails in Java.

Most programming languages like python, provide tools to send emails. The prerequisites needed for sending emails in java language are:

  • JavaMail API
  • Java Activation Framework (JAF)
  • Your SMTP server details

You must have latest versions of JavaMail and JAF. If your system does not have the latest versions of JavaMail API and Java Activation Framework (JAF) the you can download the latest versions from official java website.

Sending Email

A programmer should follow the below steps to send emails:

  • The first step is to get session object. This object stores all the necessary information of the host such as host name, its user name and password.
  • The second step is to compose the message.
  • The third step is to finally send the message.

The below example shows how to send emails through java code.

// Java code that sends email
  
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
  
  
public class SendingEmail 
{
  
   public static void main(String [] args) 
   {    
      // Defining email ID of Recipient
      String recipient = "recipient@gmail.com";
  
      // Defining email ID of Sender
      String sender = "sender@gmail.com";
  
      // Defining host as localhost
      String host = "127.0.0.1";
  
      // Defining system properties
      Properties properties = System.getProperties();
  
      // Setting up smtp mail server
      properties.setProperty("mail.smtp.host", host);
  
      // Defining session object to get properties
      Session session = Session.getDefaultInstance(properties);
  
      try 
      {
         // Defining MimeMessage object
         MimeMessage message = new MimeMessage(session);
  
         // Defining Set From Field: adding senders email to from field.
         message.setFrom(new InternetAddress(sender));
  
         // Defining Set To Field: adding recipient's email to from field.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
  
         // Defining Set Subject: subject of the email
         message.setSubject("This is email Subject");
  
         // Defining text set body of the email
         message.setText("This is a test mail");
  
         // Sending email
         Transport.send(message);
         System.out.println("Mail is successfully sent");
      }
      catch (MessagingException msgex) 
      {
         msgex.printStackTrace();
      }
   }
}

The output of the above code after compilation and execution is: