Send an email using SMTP with Java

9/13/2021

Send Email in Java Using SMTP

Go Back

How to Send Email in Java Using SMTP

Sending emails programmatically is a common requirement in Java applications. In this tutorial, we will learn how to send an email in Java using SMTP with the JavaMail API. We will cover the required dependencies, provide a step-by-step guide, and demonstrate a working example.

Prerequisites

Before we begin, ensure that you have the following libraries installed:

  • JavaMail API
  • Java Activation Framework (JAF)

These libraries are required to enable email functionality in Java.

Send Email in Java Using SMTP

Java Code to Send Email Using SMTP

Below is the Java program to send an email using SMTP.

import java.util.*;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;

class SendHTMLEmail {
    public static void main(String[] args) {
        String to = "[email protected]";
        String from = "[email protected]";
        String host = "smtp.example.com"; // Replace with SMTP server

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        Session session = Session.getDefaultInstance(properties);

        try {
            MimeMessage message = new MimeMessage(session);
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("Test Email via SMTP");
            message.setContent("<h1>This is a test email sent via Java SMTP</h1>", "text/html");
            Transport.send(message);
            System.out.println("Email sent successfully...");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Explanation

  1. Import required libraries: The javax.mail and javax.activation packages are used to handle email communication.
  2. Set SMTP server properties: The SMTP host is defined in the properties object.
  3. Create a session: A Session instance is created using the specified properties.
  4. Compose the email:
    • Set the recipient, sender, subject, and message content.
  5. Send the email: The Transport.send() method is used to dispatch the email.

Conclusion

In this article, we have demonstrated how to send an email in Java using SMTP. This is a fundamental feature for applications that require email notifications, such as password resets, alerts, or transactional emails.

Additional Resources

If you found this article helpful, follow us on Instagram, LinkedIn, Facebook, and Twitter for more updates!


Article by Developer Indian Team.

Table of content