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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)