How to Send an email Programmatically using Java

Close-up of computer screens displaying JavaScript and PHP code, featuring syntax highlighting and various programming statements for web development.

Sending emails directly from your application is a common requirement. Whether you’re building a notification system, password reset workflow, or status alert mechanism. In this article, you’ll learn how to send emails programmatically using Java by leveraging the JavaMail API (now part of jakarta.mail).

We’ll walk through a complete example that shows how to configure your email settings, authenticate with an SMTP server, and send a message using a reusable function. Whether you’re building a backend service or adding email capabilities to an existing app, this guide will give you a solid foundation for integrating email into your Java applications.

What You’ll Need (Prerequisites)

Before writing any code, make sure your environment is ready:

1. Install the Java Development Kit (JDK)

You’ll need Java 8 or later. If you don’t already have the JDK installed, you can download it here:
👉 Download the JDK

2. Add the JavaMail (Jakarta Mail) Library

The JavaMail API is not included in the JDK by default. You’ll need to add it manually or through your build tool:

  • Maven users: Add this to your pom.xml: xmlCopyEdit<dependency> <groupId>com.sun.mail</groupId> <artifactId>jakarta.mail</artifactId> <version>2.0.1</version> </dependency>
  • Manual installation:
    If you aren’t using Maven or Gradle, download the JavaMail library (e.g., version 1.6.2 or later) from the official Jakarta Mail project:
    👉 Jakarta Mail GitHub Releases After downloading, extract the ZIP file and locate mail.jar.

3. Add mail.jar to Your Project (if using Eclipse)

If you’re working in Eclipse and adding the library manually:

  1. Extract the ZIP file you downloaded
  2. Open Eclipse and select your project in the Package Explorer
  3. Right-click your project name → Build PathConfigure Build Path
  4. Go to the Libraries tab
  5. Click Add External JARs
  6. Select mail.jar from the extracted folder
  7. Click Open, then OK

Once the library is added, you’re ready to start writing the code to send your first email.

Writing Code

Now that we have all of the prerequisites installed, we can start looking at our code. Below is an example application which sends an email using the javax.mail library. This application sends through an SMTP relay that requires TLS and authentication. Some mail relays do not require either of these things. You will probably want to add some additional code to make that configurable. In this application, it is hard code to use authentication and TLS.

We have added comments throughout the code to help explain each section.

//Import the required libraries for the send email function
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

//Call the function to send your email.  This is pre-populated for using Gmail as your SMTP server.
sendEmail("smtp.gmail.com", //SMTP Server Address
"587", //SMTP Port Number
"true", //Enable Authorization
"true", //Enable TLS
"<YourAddress>@gmail.com", //Your SMTP Username
"<YourPassword>", //Your SMTP Password
"<From Address>", //Sender Address
"<To Address>", //Recipient Address
"<Subject>", //Message Subject
"<Body>"); //Message Body


//Below is the function for sending the email
static void sendEmail(
			String smtpAddress, 
			String smtpPort, 
			String enableTLS, 
			String enableAuth, 
			final String username, 
			final String password,
			String fromAddress,
			String toAddress,
			String mySubject,
			String myMessage){

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", enableTLS);
        props.put("mail.smtp.auth", enableAuth);
        props.put("mail.smtp.host", smtpAddress);
        props.put("mail.smtp.port", smtpPort);

        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromAddress));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toAddress));
            message.setSubject(mySubject);
            message.setText(myMessage);
            Transport.send(message);
        	System.out.print("Sent");

        } catch (Exception e) {
        	System.out.print(e);
        }
    }

What This Code Does

  • SMTP Properties: Configures the connection to your SMTP server, including port 587 for TLS.
  • Session Object: Authenticates using the username and password you provide.
  • MimeMessage: Constructs the actual email, including sender, recipient, subject, and body.
  • Transport.send(): Sends the email message over the network.

To send email from your Java application, you’ll need to connect to an SMTP server—this is the server responsible for delivering your messages. Most email providers (like Gmail, Outlook, SendGrid, or custom mail servers) support SMTP access, usually requiring authentication and encryption.

Summary

By now, you’ve successfully set up everything needed to send email from a Java application. You’ve:

  • Installed the Java Development Kit (JDK)
  • Downloaded and configured the JavaMail (Jakarta Mail) library
  • Written a complete Java program that connects to an SMTP server using authentication and TLS encryption
  • Created a reusable function that can be integrated into any application where email delivery is required

This basic setup forms the foundation for adding robust email functionality to your applications—whether you’re sending alerts, onboarding messages, or password reset links. As your needs grow, you can extend this example to support features like HTML content, file attachments, CC/BCC fields, or integration with cloud-based email providers like SendGrid or Amazon SES.

With this functionality in place, your application can communicate more effectively with users, support automated workflows, and improve overall system interactivity.

Elevate Your IT Efficiency with Expert Solutions

Transform Your Technology, Propel Your Business

Unlock advanced technology solutions tailored to your business needs. At Inventive HQ, we combine industry expertise with innovative practices to enhance your cybersecurity, streamline your IT operations, and leverage cloud technologies for optimal efficiency and growth.