ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to send an email through a Java application using Java Mail API ?.

Updated on September 17, 2014

Introduction

In this tutorial you will learn how to send an email through a Java application using Java Mail API (Application Programming Interface). In order to code email application client you need to download Java Mail API jar from Oracle website. This API has all the required classes such as Message, Transport, Session and InternetAddress etc, which helps in sending an email. The jar should be placed in the "classpath" of your application. In this tutorial complete video is provided. This video will provide you complete walk through of the Java code for sending an email. The code is simple to use. In order to test successfully delivery of the email, create a dummy email and send a mail through it to your personal email id. For this tutorial, we will create a dummy email such as "yournewdummyemail@gmail.com", whose username and password will be used in the code below.

Java source code - Eclipse Snapshot

Below is the video tutorial which demonstrates how to send email in Java through Java Mail API. It gives complete end-to-end description of what steps need to be followed.

Video - How to send email in Java using Java Mail API.

Java code - How to send email through a Java application

// Import javax.mail and java.util classes for this demo.
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailDemo {

	public static void main(String[] args) {

		// Create a Properties object. It stores properties such 
		// as host, authenticity, starttls enability and port etc
		// in the form of name/value pairs. 
		Properties properties = new Properties();

		// provide mail.smtp.auth as true
		properties.put("mail.smtp.auth", "true");

		// provide mail.smtp.starttls.enable as true
		properties.put("mail.smtp.starttls.enable", "true");

		// provide mail.smtp.host as smtp.gmail.com
		properties.put("mail.smtp.host", "smtp.gmail.com");

		// provide mail.smtp.port as 587
		properties.put("mail.smtp.port", "587");

		// Create Scanner object to take user inputs
		// from the console.
		Scanner scanner = new Scanner(System.in);

		// Prompt the user to enter username of gmail id.
		System.out.print("Username for Authentication : ");

		// Create a String variable username. Using scanner class
		// nextLine method take username entered by user and assign it 
		// to username variable.
		final String username = scanner.nextLine();

		// Prompt the user to enter password of gmail id.
		System.out.print("Password for Authentication : ");

		// Create a String variable password. Using scanner class
		// nextLine method take password entered by user and assign it 
		// to password variable.
		final String password = scanner.nextLine();

		// Prompt the user to enter gmail id from which mail is to be sent.
		System.out.print("From email : ");

		// Create a String variable fromEmailAddress. Using scanner class
		// nextLine method take email address entered by user and assign it 
		// to fromEmailAddress variable.
		String fromEmailAddress = scanner.nextLine();

		// Prompt the user to enter email id to which mail is to be sent.
		System.out.print("To email : ");

		// Create a String variable toEmailAddress. Using scanner class
		// nextLine method take email address entered by user and assign it 
		// to toEmailAddress variable.
		String toEmailAddress = scanner.nextLine();

		// Prompt the user to enter subject of email to be sent.
		System.out.print("Subject : ");

		// Create a String variable subject. Using scanner class
		// nextLine method take email address entered by user and assign it 
		// to subject variable.
		String subject = scanner.nextLine();

		// Prompt the user to enter message of email to be sent.
		System.out.print("Message : ");

		// Create a String variable textMessage. Using scanner class
		// nextLine method take email address entered by user and assign it 
		// to toEmailAddress variable.
		String textMessage = scanner.nextLine();

		// Creating a session instance. It requires two parameters such as 
		// properties instance created above and authenticator instance taking
		// in username and password. It requires it for authenticating user by using 
		// PasswordAuthentication class.
		Session session = Session.getDefaultInstance(properties,	new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		try {

			// Using the session instance create a message instance. 
			Message message = new MimeMessage(session);

			// Using setFrom method to set the email address to message instance. 
			// This email address would be the address from which 
			// the email is to be sent. 
			message.setFrom(new InternetAddress(fromEmailAddress));

			// Using setRecipients method to set the email address 
			// to message instance. This email address would be the 
			// address to which email is to be sent. 
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(toEmailAddress));

			// Using setSubject method to set the subject of the email in message.
			message.setSubject(subject);

			// Using setText method to set the text of the email in message.
			message.setText(textMessage);

			// Transport class has send method. Using send method email is been 
			// send to the recipients.
			Transport.send(message);

			System.out.println("\nYour message delivered successfully ....");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}

Steps to implement -

  1. Create a Properties object. It stores properties such as host, authenticity, "start tls enability" and port etc in the form of name/value pairs. Provide name/value pairs as : "mail.smtp.auth" as true, "mail.smtp.starttls.enable" as true, "mail.smtp.host" as "smtp.gmail.com", "mail.smtp.port" as 587. These properties are required to send an email through TLS.
  2. Create a Scanner object. Scanner class will read values from the console which user enters.
  3. Prompt the user to enter username of Gmail id. Create a String variable username. Using scanner class "nextLine" method, take username entered by user and assign it to username variable.
  4. Prompt the user to enter password of Gmail id. Create a String variable password. Using scanner class "nextLine" method, take password entered by user and assign it to password variable.
  5. Prompt the user to enter email id from which mail is to be sent. Create a String variable "fromEmailAddress". Using scanner class "nextLine" method, take email address entered by user and assign it to "fromEmailAddress" variable.
  6. Prompt the user to enter email id to which mail is to be sent. Create a String variable "toEmailAddress". Using scanner class "nextLine" method, take email address entered by user and assign it to "toEmailAddress" variable.
  7. Prompt the user to enter subject of email to be sent. Create a String variable subject. Using scanner class "nextLine" method, take subject entered by user and assign it to subject variable.
  8. Prompt the user to enter message of email to be sent. Create a String variable "textMessage". Using scanner class "nextLine" method, take message entered by user and assign it to "textMessage" variable.
  9. Creating a session instance. It requires two parameters such as properties instance and authenticator instance taking in username and password. It requires it for authenticating user by using PasswordAuthentication class.
  10. Using the session instance, create a message instance.
  11. Using "setFrom" method, to set the email address to message instance. This email address would be the address from which the email is to be sent.
  12. Using "setRecipients" method, to set the email address to message instance. This email address would be the address to which email is to be sent.
  13. Using "setSubject" method, to set the subject of the email in message.
  14. Using "setText" method, to set the text of the email in message.
  15. Transport class has static send method. Using send method, email is been send to the recipients.

Output of the program -

Explanation of output :

After running demo class, it asks for the few details such as,

  1. Username
  2. Password
  3. From Email
  4. To Email
  5. Subject
  6. Text Message

After providing correct details to program, email will be send successfully to the recipient. The proof of successfully email delivery is shown in the figure below.

Email received at recipient : Yahoo Mail Snapshot

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article