Home/Blog/Java Send Email Programmatically | SMTP Guide
Automation

Java Send Email Programmatically | SMTP Guide

Complete guide with setup instructions and code examples for SMTP integration

Java Send Email Programmatically | SMTP Guide

Sending emails directly from your application is a common requirement for notification systems, password reset workflows, and status alerts. 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 provides a solid foundation for integrating email into your Java applications.

Prerequisites and Setup

Before writing any code, make sure your environment is ready with the necessary tools and libraries.

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 from the official Oracle website.

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:

<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 from the official Jakarta Mail project and add mail.jar to your project’s build path.

Complete Java Email Code Example

Here’s a complete example application that sends an email using the javax.mail library. This application sends through an SMTP relay that requires TLS and authentication.

//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

The sendEmail Function

//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);
    }
}

How the Code Works

  • 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.

Security Note: Always use environment variables or secure configuration files to store SMTP credentials. Never hardcode passwords in your source code.

Next Steps and Extensions

You’ve successfully set up everything needed to send email from a Java application. 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.

Key Accomplishments

  • 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

Advanced Features to Explore

  • HTML content formatting for rich email templates
  • File attachments for documents and images
  • CC/BCC fields for multiple recipients
  • Integration with cloud-based email providers like SendGrid or Amazon SES
  • Email templates and dynamic content generation

Frequently Asked Questions

Find answers to common questions

JavaMail API for: simple internal emails (notifications, alerts), low volume (<1,000 emails/day), no deliverability concerns (emails to your organization), learning/testing. Third-party services (SendGrid, AWS SES, Mailgun) for: customer-facing emails (transactional, marketing), high volume (>1,000/day), deliverability critical (emails must reach inbox not spam), need tracking (open rates, click rates), professional templates. Cost comparison: JavaMail is free (but you handle SMTP server, IP reputation), third-party starts free (100-1,000 emails/day free tier), then $10-$100/month for 10K-100K emails. For production customer emails: use third-party service—they handle: IP reputation management, bounce/spam complaint handling, deliverability optimization, compliance (unsubscribe links, CAN-SPAM). JavaMail for internal notifications only.

Transform Your IT with Automation

Streamline operations, reduce manual tasks, and improve security with intelligent automation.