Skip to main content
Home/Blog/Automation/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

To send email programmatically in Java you add the Jakarta Mail (formerly JavaMail) library, build a Properties object describing your SMTP server, create an authenticated Session, wrap your text in a MimeMessage, and call Transport.send(). The JDK ships no SMTP client of its own, so that external dependency is mandatory — everything else is a handful of configuration keys (mail.smtp.host, mail.smtp.port, mail.smtp.auth, mail.smtp.starttls.enable) and a username/password pair supplied through an Authenticator.

That's the summary an AI Overview gives you. What it can't show you is where this actually breaks: the javax.mail vs jakarta.mail namespace trap that produces "package does not exist," the fact that Gmail stopped accepting plain passwords in 2022, and the reason a "Sent" message never reaches the inbox. Below is the send flow as a diagram, a version-vs-namespace decision table, the corrected code, and a symptom→cause→fix table for the errors you'll actually hit.

Email Setup Wizard

Set up email authentication with guided SPF, DKIM, and DMARC configuration for your domain

Open the full Email Setup Wizard →

The SMTP send flow at a glance

How a Java program hands an email to an SMTP server Your Java code builds a session, opens a TLS connection to the SMTP relay, authenticates, transfers the message, and the relay queues it for delivery. Java app Properties + Session + MimeMessage SMTP relay port 587 STARTTLS + AUTH login Recipient inbox queue SPF / DKIM checked Transport.send() relay + deliver 🔒 TLS Auth fails here → "535 5.7.8" error No SPF/DKIM → spam / dropped

The two red labels mark the failure points that a happy-path tutorial never mentions: authentication rejection at the relay, and silent spam-foldering after the relay accepts the message. Transport.send() returning without an exception means only that step two succeeded — not that the mail landed.

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. Any modern JDK (Oracle, Adoptium/Temurin, Amazon Corretto, or the one bundled with your IDE) works — Jakarta Mail has no exotic runtime requirements.

Add the Jakarta Mail (JavaMail) Library — mind the namespace

The mail API is not included in the JDK. You add it through your build tool, but which artifact you pick determines which import statements compile. This is the single most common thing people get wrong.

<!-- Jakarta Mail 2.x  ->  imports use jakarta.mail.* -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>2.0.1</version>
</dependency>

If instead your code imports javax.mail.* (as the classic example below does), you need the 1.6.x artifact, which keeps the old namespace:

<!-- JavaMail 1.6.x  ->  imports use javax.mail.* -->
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>jakarta.mail</artifactId>
    <version>1.6.7</version>
</dependency>

Manual install: If you aren't using Maven or Gradle, download the matching JAR from the Eclipse Jakarta Mail project and add it to your project's build path.

Which version should I use?

JavaMail 1.6.xJakarta Mail 2.x
Import namespaceimport javax.mail.*;import jakarta.mail.*;
Maven version1.6.72.0.1 (or newer)
Min. JavaJava 8Java 8 (2.0.x); Java 11+ for 2.1.x
Framework fitSpring Boot 2.x, Jakarta EE 8, legacy appsSpring Boot 3.x, Jakarta EE 9+, new projects
Which should I use?Only when locked to an existing javax.* codebaseDefault for any new project — it's the maintained line

The rule of thumb: new project → Jakarta Mail 2.x with jakarta.mail.* imports. Only reach for 1.6.x when you're bound to an older javax-based framework. Never mix the two — that mismatch is exactly what produces package javax.mail does not exist even though the dependency is on the classpath.

Complete Java Email Code Example

This class sends through an SMTP relay that requires STARTTLS and authentication. It uses the classic javax.mail namespace, so pair it with the 1.6.7 dependency above. Set SMTP_USER, SMTP_PASS, SMTP_FROM, and SMTP_TO in the environment before running it; use an app password where your provider requires one.

import java.util.Properties;
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 SendEmail {
    public static void main(String[] args) throws MessagingException {
        sendEmail("smtp.gmail.com", "587", "true", "true",
                requiredEnv("SMTP_USER"), requiredEnv("SMTP_PASS"),
                requiredEnv("SMTP_FROM"), requiredEnv("SMTP_TO"),
                "Test message", "Hello from Java");
    }

    private static String requiredEnv(String name) {
        String value = System.getenv(name);
        if (value == null || value.isEmpty()) {
            throw new IllegalArgumentException("Missing environment variable: " + name);
        }
        return value;
    }

    static void sendEmail(String smtpAddress, String smtpPort,
            String enableTLS, String enableAuth, String username,
            String password, String fromAddress, String toAddress,
            String subject, String body) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpAddress);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", enableAuth);
        props.put("mail.smtp.starttls.enable", enableTLS);
        props.put("mail.smtp.starttls.required", enableTLS);

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

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toAddress));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
        System.out.println("Accepted by SMTP relay");
    }
}

mail.smtp.starttls.required makes the send fail if the relay cannot negotiate STARTTLS. Replace the SMTP host and port with those of your relay.

How the Code Works

  • SMTP Properties configure the connection — host, port 587, and the STARTTLS/auth toggles.
  • Session binds those properties to an Authenticator that supplies credentials on demand.
  • MimeMessage builds the actual envelope: from, to, subject, and body.
  • Transport.send() opens the connection, upgrades to TLS, authenticates, and streams the message to the relay.

To send from Java you always connect to an SMTP server — the machine responsible for relaying your message onward. Gmail, Outlook, SendGrid, Amazon SES, and self-hosted Postfix all speak SMTP, and all of them require authentication plus encryption for authenticated client submission.

Security note: Store SMTP credentials in environment variables or a secrets manager, as shown above with System.getenv. Never hardcode passwords — they leak through Git history and decompiled JARs.

Troubleshooting: symptom → cause → fix

SymptomLikely causeFix
package javax.mail does not existNamespace/version mismatch, or dependency missingMatch imports to the artifact: javax.mail.* ↔ 1.6.x, jakarta.mail.* ↔ 2.x
535-5.7.8 Username and Password not accepted (Gmail)Using account password after Sept 2022 cutoffEnable 2-Step Verification, generate a 16-digit App Password, use it as the SMTP password
javax.mail.AuthenticationFailedExceptionWrong credentials, or auth disabled on the relayVerify username/password; set mail.smtp.auth=true
Hangs then couldn't connect to host, port: 587Port blocked by firewall/ISP, or wrong hostTest with telnet host 587; try 465 with mail.smtp.ssl.enable=true
MessagingException: Could not convert socket to TLSRelay requires TLS but STARTTLS not setSet mail.smtp.starttls.enable=true (or use port 465 + implicit SSL)
Prints "Sent" but mail never arrivesMissing SPF/DKIM/DMARC → filtered as spamAdd authentication records to the sending domain; check the recipient's spam folder
IllegalStateException: Not connected on reuseReusing a closed Transport across sendsCall Transport.send() per message, or manage connect()/close() explicitly

Next Steps and Extensions

You now have a reusable function that connects to any SMTP relay with authentication and TLS — a foundation for alerts, onboarding mail, and password-reset links. From here:

  • HTML bodies — swap setText for setContent(html, "text/html; charset=utf-8").
  • Attachments — build a MimeMultipart with a body part per file.
  • CC/BCC — add recipients with Message.RecipientType.CC / .BCC.
  • Provider APIs — for volume or deliverability guarantees, move to SendGrid or Amazon SES over their REST APIs instead of raw SMTP.
  • Deliverability — the code is the easy part; getting mail into the inbox is a DNS problem. See the related guides below on SPF/DKIM/DMARC and delivery troubleshooting.

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.

SMTP: traditional email protocol (JavaMail uses SMTP to connect to email server), works with any email server, slower (TCP connection overhead), limited features. API-based (SendGrid API, AWS SES API): RESTful HTTP calls, faster (no SMTP connection), richer features (templates, tracking, A/B testing, analytics), service-specific (code tied to vendor). Use SMTP when: working with any email server (Gmail, Office 365, self-hosted), legacy code using JavaMail, simple email sending. Use API when: using third-party email service with API (SendGrid, Mailgun), need advanced features (templates, tracking), want better performance (HTTP vs SMTP). For modern apps: API is better (cleaner code, better features). For simple internal emails or working with corporate Exchange server: SMTP with JavaMail is sufficient.

Authentication: configure SPF record (allows your SMTP server to send for your domain), DKIM signing (cryptographic proof email wasn't modified), DMARC policy (tells recipients what to do with failed authentication). Content: avoid spam trigger words (free, urgent, click here, limited time), include unsubscribe link for marketing emails, use real From address (no-reply@ is suspicious), keep HTML clean (avoid too many images, links). Infrastructure: use dedicated email service with good IP reputation (SendGrid, AWS SES—they maintain IP reputation), warm up new IP (start with low volume, gradually increase), monitor bounce rates (remove invalid addresses, high bounce rate tanks reputation). Test: send to mail-tester.com (scores deliverability, identifies issues), check spam folder on Gmail/Outlook, monitor delivery rates. For production: use SendGrid/SES instead of sending from application server IP (their IPs have established reputation).

Use message queue (RabbitMQ, AWS SQS) for reliable email delivery: application puts email in queue, background worker processes queue and sends emails, failures get retried (exponential backoff—retry after 1min, 5min, 30min, 2hr), permanent failures after N attempts go to dead-letter queue for manual review. This prevents: blocking application thread waiting for SMTP (email sending takes 1-5 seconds), losing emails when SMTP server is down (queued for retry), overwhelming SMTP server (worker processes at controlled rate). Simple approach without queue: catch SMTPSendFailedException, log failure, retry with exponential backoff (don't retry immediately—SMTP server down might stay down for minutes). Don't: throw exception up to user on email failure (they don't care why email failed), retry forever (permanent failures should eventually stop). Do: log all email attempts (audit trail), monitor failed emails (alert if failure rate spikes), have dead-letter handling for permanent failures.

Use MimeMultipart with related content: create MimeBodyPart for HTML content, create MimeBodyPart for each image (set Content-ID header), reference images in HTML via cid: URLs (<img src="cid:logo">). This embeds images in email (better than linking external URLs which many email clients block by default). Alternative: link to hosted images (simpler code, requires images hosted on public URL, some clients block external images). Modern approach: use email service API with templates (SendGrid, Mailgun—upload template with images, send email with template ID and variables). DIY HTML emails are painful—lots of code for attachments, multipart handling, encoding. For simple HTML: inline CSS, no images (best email client compatibility). For rich HTML with images: use email service templates (they handle multipart encoding, image embedding, mobile-responsive HTML). Only use JavaMail for HTML if you can't use third-party service.

Transform Your IT with Automation

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