• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to Send Email using Java – JavaMail | Plain Text and HTML Email

October 29, 2018 by javainterviewpoint Leave a Comment

In this tutorial, we will learn how to send email using Java. In order to send mail in Java we need to have the JavaMail API dependency added to the class path. 

Folder Structure:

Send Email using Java

    1. Create a new Maven QuickStartProject  “JavaEmail” and create a package for our src files “com.javainterviewpoint“
    2. Now add the following dependency in the POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.javainterviewpoint</groupId>
	<artifactId>JavaEmail</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>JavaEmail</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.6.0</version>
		</dependency>
	</dependencies>
</project>
  1. Create the Java classes SendingEmail.java and SendEmailHTMLTemplate.java under  com.javainterviewpoint folder.

Other Posts which you may like …

  • Write Excel File in Java using POI
  • Read Excel File in Java using POI
  • Jackson 2 JSON Parser – Convert JSON to/from Java Object
  • How to Convert JSON to / from Java Map using JACKSON
  • Jackson Tree Model Example – JsonNode
  • Jackson Streaming API Example | Read and Write JSON
  • Jackson JSON Example | ObjectMapper and @JSONView
  • How to Parse JSON to/from Java Object using Boon JSON Parser
  • How to Read and Write JSON using GSON
  • How to write JSON object to File in Java?
  • How to read JSON file in Java – JSONObject and JSONArray
  • Jersey Jackson JSON Tutorial
  • Spring REST Hello World Example – JSON and XML responses
  • How to Convert Java Object to JSON using JAXB
  • JAX-RS REST @Consumes both XML and JSON Example
  • JAX-RS REST @Produces both XML and JSON Example

Send Email using Java

JavaMail Plain Text

package com.javainterviewpoint;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendingEmail
{
    public static void main(String[] args)
    {
        // Receiver's email ID
        String receiver = "[email protected]";

        // Sender's email ID
        String sender = "[email protected]";

        // Sending email from localhost
        String host = "localhost";

        // Port of SMTP
        String port = "25";

        // Getting system properties
        Properties properties = System.getProperties();

        // Setting up the mail server
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);

        // Get default session object
        Session session = Session.getDefaultInstance(properties);

        try
        {
            // Create MimeMessage object
            MimeMessage message = new MimeMessage(session);

            // Set the Senders mail to From
            message.setFrom(new InternetAddress(sender));

            // Set the recipients email address
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));

            // Subject of the email
            message.setSubject("Java Send Email Example");

            // Body of the email
            message.setText("Welcome to Java Interviewpoint");

            // Send email
            Transport.send(message);
            System.out.println("Mail sent successfully");
        } catch (MessagingException me)
        {
            me.printStackTrace();
        }
    }
}
  • Create variables for sender, receiver, host and port
  • Get the properties from the System.getProperties()
Properties properties = System.getProperties();
  • Set the “mail.smtp.host” and “mail.smtp.port” to the properties instance using the setProperty() method
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
  • Get the Java Mail Session instance passing the properties to the getDefaultInstance() method
Session session = Session.getDefaultInstance(properties);
  • Create a new MimeMessage object passing the session
MimeMessage message = new MimeMessage(session);
  • In order to set the sender and receivers email address we will be using the InternetAddress class.
  • Senders email address is set using the setFrom() method of the MimeMessage class, it takes up the InternetAddress class, we will pass the sender string to its constructor.
message.setFrom(new InternetAddress(sender));
  • The recipients email address is passed to the addRecipient() method. The recipient type can be Message.RecipientType.TO, Message.RecipientType.CC or Message.RecipientType.BCC
message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
  • Set the subject with setSubject() and set the plaintext body content with setText()
message.setSubject("Java Send Email Example");
message.setText("Welcome to Java Interviewpoint");
  • Now call the send() method of the Transport class passing the message (MimeMessage) to send the mail
Transport.send(message);

Output:

Mail sent successfully

Note: 

You should be having any SMTP server running, if not you will be getting the below error

 com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
  nested exception is:
	java.net.ConnectException: Connection refused: connect
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2194)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:726)
	at javax.mail.Service.connect(Service.java:366)
	at javax.mail.Service.connect(Service.java:246)
	at javax.mail.Service.connect(Service.java:195)
	at javax.mail.Transport.send0(Transport.java:254)
	at javax.mail.Transport.send(Transport.java:124)

In my case, i am using Apache James SMTP Server

JavaMail – Java HTML Email template

package com.javainterviewpoint;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmailHTMLTemplate
{
    public static void main(String[] args)
    {
        // Receiver's email ID
        String receiver = "[email protected]";

        // Sender's email ID
        String sender = "[email protected]";

        // Sending email from localhost
        String host = "localhost";

        // Port of SMTP
        String port = "25";

        // Getting system properties
        Properties properties = System.getProperties();

        // Setting up the mail server
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", port);

        // Create default session object
        Session session = Session.getDefaultInstance(properties);

        try
        {
            // Create MimeMessage object
            MimeMessage message = new MimeMessage(session);

            // Set the Senders mail to From
            message.setFrom(new InternetAddress(sender));

            // Set the recipients email address
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));

            // Subject of the email
            message.setSubject("Java Send Email Example");

            // HTML email template
            String messageBody = "<h3>Welcome to JavaInterviewPoint!</h3><br>";
            messageBody += "<b>Java Mail Template example</b><br>";
            
            // Body of the HTML Email
            message.setContent(messageBody, "text/html");

            // Send email
            Transport.send(message);
            System.out.println("Mail sent successfully");
        } catch (MessagingException me)
        {
            me.printStackTrace();
        }
    }
}

Filed Under: Core Java, Java Tagged With: HTML Email, JavaMail, Plain Text, Send Email using Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·