Sending Email from Java: SMTP and Jakarta Mail
How email delivery works from Java: the SMTP conversation (EHLO, MAIL FROM, RCPT TO, DATA), envelopes vs. headers, MIME messages with UTF-8 subjects and Base64 attachments, ports, STARTTLS and authentication, and sending with Jakarta Mail and Angus Mail.
kvi5hnuCode Sprout team member9 min readOn this page
The JDK has no email API. In practice, you use Jakarta Mail (formerly JavaMail), a library that handles the protocol, MIME formatting, TLS and authentication. Understanding what the library does underneath helps a lot when mail doesn't arrive, though, and the protocol is a nice example of a classic text-based network protocol. This article first walks through SMTP and MIME by hand, with a small client talking to a fake local server, and then shows the Jakarta Mail code you would use in a real application.
How mail is delivered
A program doesn't deliver mail to the recipient's inbox itself. It hands the message to a mail submission server (your company's or your provider's, such as an Office 365 or Gmail relay, or a transactional service). That server looks up the recipient domain's MX records in DNS and relays the message to the receiving server, which stores it until the recipient's mail program fetches it with IMAP or POP3. SMTP (Simple Mail Transfer Protocol, RFC 5321) is the protocol for the sending and relaying steps.

| Port | Use |
|---|---|
| 587 | submission by clients, starting in plain text and switching to TLS with STARTTLS, then authenticating |
| 465 | submission over TLS from the first byte ("implicit TLS", recommended by RFC 8314) |
| 25 | server-to-server relaying. Often blocked for ordinary machines and cloud VMs |
The SMTP conversation
SMTP is line-based. The client sends commands, and the server answers each with a three-digit code and some text. Codes starting with 2 mean success, 3 means "go on", 4 is a temporary failure (try later) and 5 a permanent one. A reply can span several lines, and every line except the last has a - after the code.
S: 220 mail.example.com ESMTP ready
C: EHLO client.example.org
S: 250-mail.example.com
S: 250-STARTTLS
S: 250 AUTH PLAIN LOGIN
C: MAIL FROM:<ada@example.org>
S: 250 OK
C: RCPT TO:<bob@example.com>
S: 250 OK
C: DATA
S: 354 End data with <CR><LF>.<CR><LF>
C: (headers, blank line, body)
C: .
S: 250 OK queued
C: QUIT
S: 221 Bye
EHLOintroduces the client. The reply lists extensions such asSTARTTLS,AUTH,SIZEand8BITMIME. (The olderHELOgets no extension list.)MAIL FROMgives the sender, and eachRCPT TOone recipient. A server can reject single recipients and accept others.- After
DATA, the client sends the message itself and ends it with a line containing only a dot. A line of the message that begins with a dot gets an extra dot (dot-stuffing), and the receiver removes it again. - Lines end with CR LF.
With STARTTLS, the client upgrades the plain connection to TLS (as in article 50) and sends EHLO again over the encrypted channel. Then AUTH PLAIN sends a Base64-encoded user name and password, or AUTH XOAUTH2 sends an OAuth 2 token. Major providers, Microsoft and Google included, have been turning off password authentication for SMTP in favor of OAuth or app-specific passwords, so check your provider's current rules.
MIME: what goes after DATA
The message format (RFC 5322) is header lines, a blank line, and the body. Originally that meant 7-bit ASCII text only. MIME (Multipurpose Internet Mail Extensions) adds everything else:
MIME-Version: 1.0andContent-Typesay what the body is, for exampletext/plain; charset=UTF-8ortext/html.Content-Transfer-Encodingsays how the bytes are encoded for transport:7bit,8bit(only if the server announces8BITMIMEand the client then sendsMAIL FROM:<...> BODY=8BITMIME),quoted-printableorbase64.- A
multipart/mixedbody contains several parts separated by a boundary line--boundary, and ends with--boundary--. Each part has its own headers. Attachments are parts withContent-Disposition: attachment; filename="...", usually Base64-encoded in lines of at most 76 characters, which is exactly whatBase64.getMimeEncoder()produces.multipart/alternativeoffers the same content as plain text and as HTML. - Headers must be ASCII, so non-ASCII text in a subject or name is written as an encoded word (RFC 2047):
=?UTF-8?B?<base64>?=or=?UTF-8?Q?<quoted-printable>?=. Servers that announceSMTPUTF8(RFC 6531) also accept UTF-8 directly, including in addresses, if the client requests it withMAIL FROM:<...> SMTPUTF8.
The program
The demo runs a fake mail server on a loopback port that accepts mail only for @mail.test addresses and stores what it receives. The client builds a MIME message by hand: a UTF-8 subject as an encoded word, a plain-text part containing a line that starts with a dot, and a Base64 CSV attachment. It then runs the SMTP dialog, printing each client (C:) and server (S:) line. One recipient is rejected and the rest still get the message. At the end, the program shows what the server stored and decodes the subject and attachment again.
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
public class Solution {
// ---------------- a fake mail server that accepts one session ----------------
record Mail(String from, List<String> to, String data) { }
static ServerSocket startFakeSmtpServer(BlockingQueue<Mail> inbox) throws IOException {
var server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
try (server; Socket s = server.accept();
var in = new BufferedReader(new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8));
var out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8), true)) {
out.print("220 mail.test ESMTP fake server ready\r\n"); out.flush();
String from = null;
List<String> to = new ArrayList<>();
String line;
while ((line = in.readLine()) != null) {
String cmd = line.toUpperCase(Locale.ROOT);
if (cmd.startsWith("EHLO")) {
out.print("250-mail.test greets " + line.substring(5) + "\r\n250-SIZE 1000000\r\n250-8BITMIME\r\n250 SMTPUTF8\r\n");
} else if (cmd.startsWith("MAIL FROM:")) {
from = line.substring(10); to.clear();
out.print("250 OK\r\n");
} else if (cmd.startsWith("RCPT TO:")) {
String rcpt = line.substring(8);
if (rcpt.contains("@mail.test")) { to.add(rcpt); out.print("250 OK\r\n"); }
else out.print("550 5.1.1 no such user here " + rcpt + "\r\n");
} else if (cmd.equals("DATA")) {
if (to.isEmpty()) { out.print("554 no valid recipients\r\n"); out.flush(); continue; }
out.print("354 end data with <CR><LF>.<CR><LF>\r\n"); out.flush();
var data = new StringBuilder();
for (String d = in.readLine(); !d.equals("."); d = in.readLine())
data.append(d.startsWith("..") ? d.substring(1) : d).append("\n"); // undo dot-stuffing
inbox.add(new Mail(from, List.copyOf(to), data.toString()));
out.print("250 OK queued as 1\r\n");
} else if (cmd.equals("QUIT")) {
out.print("221 bye\r\n"); out.flush();
break;
} else {
out.print("502 command not implemented\r\n");
}
out.flush();
}
} catch (IOException e) {
System.out.println("server: " + e);
}
});
return server;
}
// ---------------- a minimal SMTP client ----------------
static class SmtpClient implements Closeable {
private final Socket socket;
private final BufferedReader in;
private final Writer out;
SmtpClient(String host, int port) throws IOException {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), 2000);
socket.setSoTimeout(5000);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
out = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
expect(220);
}
// reads a (possibly multi-line) reply such as "250-..." "250 ..." and checks the code
int expect(int... ok) throws IOException {
String line;
do {
line = in.readLine();
System.out.println("S: " + line);
} while (line.charAt(3) == '-');
int code = Integer.parseInt(line.substring(0, 3));
for (int c : ok) if (c == code) return code;
throw new IOException("unexpected reply " + line);
}
int command(String cmd, int... ok) throws IOException {
System.out.println("C: " + cmd);
out.write(cmd + "\r\n");
out.flush();
return expect(ok);
}
void send(String from, List<String> recipients, String message) throws IOException {
command("EHLO client.test", 250);
command("MAIL FROM:<" + from + ">", 250);
int accepted = 0;
for (String r : recipients) {
try { command("RCPT TO:<" + r + ">", 250, 251); accepted++; }
catch (IOException e) { System.out.println(" (rejected, continuing)"); }
}
if (accepted == 0) throw new IOException("no recipient accepted");
command("DATA", 354);
System.out.println("C: <" + message.lines().count() + " lines of message>");
for (String line : message.split("\r\n", -1))
out.write((line.startsWith(".") ? "." + line : line) + "\r\n"); // dot-stuffing
out.write(".\r\n");
out.flush();
expect(250);
}
@Override public void close() throws IOException {
try { command("QUIT", 221); } finally { socket.close(); }
}
}
// ---------------- building a MIME message ----------------
static String encodeWord(String text) { // RFC 2047 for non-ASCII headers
boolean ascii = text.chars().allMatch(c -> c < 128);
return ascii ? text : "=?UTF-8?B?" + Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8)) + "?=";
}
static String buildMessage(String from, List<String> to, String subject, String body, String fileName, byte[] attachment) {
String boundary = "=_boundary_42"; // fixed so the output is repeatable
var m = new StringBuilder();
m.append("From: ").append(from).append("\r\n");
m.append("To: ").append(String.join(", ", to)).append("\r\n");
m.append("Subject: ").append(encodeWord(subject)).append("\r\n");
m.append("Date: Sat, 14 Nov 2026 09:30:00 +0000\r\n");
m.append("MIME-Version: 1.0\r\n");
m.append("Content-Type: multipart/mixed; boundary=\"").append(boundary).append("\"\r\n\r\n");
m.append("--").append(boundary).append("\r\n");
m.append("Content-Type: text/plain; charset=UTF-8\r\n");
m.append("Content-Transfer-Encoding: 8bit\r\n\r\n");
m.append(body.replace("\n", "\r\n")).append("\r\n");
m.append("--").append(boundary).append("\r\n");
m.append("Content-Type: text/csv; name=\"").append(fileName).append("\"\r\n");
m.append("Content-Disposition: attachment; filename=\"").append(fileName).append("\"\r\n");
m.append("Content-Transfer-Encoding: base64\r\n\r\n");
m.append(Base64.getMimeEncoder().encodeToString(attachment)).append("\r\n"); // 76-char lines
m.append("--").append(boundary).append("--\r\n");
return m.toString();
}
public static void main(String[] args) throws Exception {
var inbox = new LinkedBlockingQueue<Mail>();
ServerSocket server = startFakeSmtpServer(inbox);
String body = """
Hi team,
the report is attached.
.this line starts with a dot and must survive
Grüße, Ada""";
byte[] csv = "month,sales\nOctober,1200\nNovember,1350\n".getBytes(StandardCharsets.UTF_8);
List<String> to = List.of("bob@mail.test", "nobody@elsewhere.example", "carol@mail.test");
String message = buildMessage("ada@mail.test", to, "Monatsbericht – November", body, "sales.csv", csv);
try (var smtp = new SmtpClient("127.0.0.1", server.getLocalPort())) {
smtp.send("ada@mail.test", to, message);
}
Mail mail = inbox.poll(5, TimeUnit.SECONDS);
System.out.println("--- the server received ---");
System.out.println("envelope from " + mail.from() + " to " + mail.to());
System.out.print(mail.data());
System.out.println("--- decoding it again ---");
String subjectLine = mail.data().lines().filter(l -> l.startsWith("Subject: ")).findFirst().orElseThrow();
String encoded = subjectLine.substring("Subject: =?UTF-8?B?".length(), subjectLine.length() - 2);
System.out.println("subject: " + new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8));
String[] parts = mail.data().split("--=_boundary_42");
String attachmentPart = parts[2];
String base64 = attachmentPart.substring(attachmentPart.indexOf("\n\n") + 2).strip();
System.out.print("attachment:\n" + new String(Base64.getMimeDecoder().decode(base64), StandardCharsets.UTF_8));
}
}
S: 220 mail.test ESMTP fake server ready
C: EHLO client.test
S: 250-mail.test greets client.test
S: 250-SIZE 1000000
S: 250-8BITMIME
S: 250 SMTPUTF8
C: MAIL FROM:<ada@mail.test>
S: 250 OK
C: RCPT TO:<bob@mail.test>
S: 250 OK
C: RCPT TO:<nobody@elsewhere.example>
S: 550 5.1.1 no such user here <nobody@elsewhere.example>
(rejected, continuing)
C: RCPT TO:<carol@mail.test>
S: 250 OK
C: DATA
S: 354 end data with <CR><LF>.<CR><LF>
C: <23 lines of message>
S: 250 OK queued as 1
C: QUIT
S: 221 bye
--- the server received ---
envelope from <ada@mail.test> to [<bob@mail.test>, <carol@mail.test>]
From: ada@mail.test
To: bob@mail.test, nobody@elsewhere.example, carol@mail.test
Subject: =?UTF-8?B?TW9uYXRzYmVyaWNodCDigJMgTm92ZW1iZXI=?=
Date: Sat, 14 Nov 2026 09:30:00 +0000
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="=_boundary_42"
--=_boundary_42
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Hi team,
the report is attached.
.this line starts with a dot and must survive
Grüße, Ada
--=_boundary_42
Content-Type: text/csv; name="sales.csv"
Content-Disposition: attachment; filename="sales.csv"
Content-Transfer-Encoding: base64
bW9udGgsc2FsZXMKT2N0b2JlciwxMjAwCk5vdmVtYmVyLDEzNTAK
--=_boundary_42--
--- decoding it again ---
subject: Monatsbericht – November
attachment:
month,sales
October,1200
November,1350
Notice that the rejected address still appears in the To: header. Headers and envelope really are independent.
Jakarta Mail
Jakarta Mail is the standard Java mail API. Version 2.x uses the package jakarta.mail, while the old JavaMail 1.6 used javax.mail. The API and its implementation are separate artifacts. The usual implementation is Eclipse Angus Mail, so with Maven you add org.eclipse.angus:angus-mail, which brings in the API jakarta.mail:jakarta.mail-api. It is an external dependency, so this code is not runnable here:
import jakarta.mail.*;
import jakarta.mail.internet.*;
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true"); // refuse to continue without TLS
Session session = Session.getInstance(props, new Authenticator() {
@Override protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password); // read from configuration, not source code
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("ada@example.org", "Ada Lovelace"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("bob@example.com, carol@example.com"));
message.setSubject("Monatsbericht – November", "UTF-8");
MimeBodyPart text = new MimeBodyPart();
text.setText("The report is attached.", "UTF-8");
MimeBodyPart attachment = new MimeBodyPart();
attachment.attachFile(Path.of("sales.csv").toFile());
message.setContent(new MimeMultipart(text, attachment));
Transport.send(message);
The library handles the steps from the demo: it picks the envelope from the recipients (unless you pass addresses explicitly to Transport.send(message, addresses)), encodes headers, chooses transfer encodings, builds the multipart structure and runs the SMTP dialog with TLS and authentication. For implicit TLS on port 465, use the protocol smtps or set mail.smtp.ssl.enable to true. SendFailedException reports which addresses were invalid, sent or unsent. Setting mail.debug to true prints the protocol conversation, which looks just like the demo output.
Common questions
Why does my mail land in the spam folder or get rejected?
Receiving servers check that the sending domain authorizes your server (SPF), that the message is signed (DKIM), and that the domain's policy accepts the result (DMARC). Send through your domain's official submission server or a transactional service that is set up for your domain, use a From address of that domain, and avoid spam-like content.
Which port should I use: 25, 465 or 587? 587 with STARTTLS (submission) or 465 with implicit TLS (submissions) for programs that send through a provider. Port 25 is for server-to-server relay and is often blocked for home and cloud networks.
How do I send HTML mail with a plain-text fallback?
Use multipart/alternative with a text/plain part first and a text/html part second. Mail programs show the last part they can render. To include images referenced by the HTML, nest that inside multipart/related with Content-ID headers.
How do I test mail sending without a real server? Use a local fake SMTP server such as the demo's, or tools like GreenMail (embeddable in tests) or Mailpit (a container that captures messages and shows them in a web UI).
Can I read mail with Java?
Yes, with Jakarta Mail's IMAP (imaps) or POP3 provider: get a Store, open a Folder and read Message objects. Many providers require OAuth 2 for IMAP today, as for SMTP.
API reference
| API / command | Purpose |
|---|---|
EHLO, MAIL FROM:<..>, RCPT TO:<..>, DATA, ., QUIT | the SMTP dialog |
STARTTLS, AUTH PLAIN, AUTH XOAUTH2 | encryption and login |
MIME-Version, Content-Type, Content-Transfer-Encoding, Content-Disposition | MIME headers |
=?UTF-8?B?...?= | encoded words for non-ASCII header text |
Base64.getMimeEncoder(), getMimeDecoder() | MIME-style Base64 |
jakarta.mail.Session.getInstance(props, authenticator) | mail configuration |
MimeMessage.setFrom, setRecipients, setSubject, setText, setContent | build a message |
MimeBodyPart, MimeMultipart, attachFile | multipart messages and attachments |
Transport.send(message) | send it |
mail.smtp.host, port, auth, starttls.enable, starttls.required, ssl.enable, mail.debug | common properties |
Summary
- Programs submit mail over SMTP to a submission server (port 587 with STARTTLS or 465 with TLS), which relays it onward.
- SMTP is a line-based dialog of commands and three-digit replies. Messages end with a lone dot, and lines starting with a dot are dot-stuffed.
- The envelope (
MAIL FROM,RCPT TO) decides delivery. TheFrom/Toheaders are only for display. - MIME describes content types, transfer encodings, multipart bodies, attachments and encoded words for non-ASCII headers.
- In applications, use Jakarta Mail (with Angus Mail) or a mail service. Configure TLS and authentication, and use
mail.debugto troubleshoot.
Practice Questions
How does Bcc work in terms of the SMTP envelope and the message headers?
The client issues a RCPT TO for the Bcc recipient, so the server delivers a copy, but the message headers don't mention that address. The other recipients only see the headers, so they can't tell. Mail libraries remove the Bcc: header before sending for exactly this reason.
Your message body contains a line consisting of just ".". What would happen without dot-stuffing?
The server would take that line as the end of the message. The rest of the body would be lost and the remaining lines would be interpreted as SMTP commands. Dot-stuffing sends it as "..", and the server removes the extra dot.
What is the difference between a 450 and a 550 reply to RCPT TO, and how should a sender react?
4xx codes are temporary failures, such as a full mailbox or greylisting, and the sender should try again later. 5xx codes are permanent, such as an unknown user, and retrying won't help, so the sender should report the failure.
How do you put the subject "Café ☕" into a mail header?
Headers must be ASCII, so encode it as an RFC 2047 encoded word: =?UTF-8?B? plus the Base64 of the UTF-8 bytes plus ?=. Jakarta Mail does this automatically with setSubject(subject, "UTF-8"). If the server announces SMTPUTF8 and the client requests it on MAIL FROM, raw UTF-8 headers are also allowed.
Your Jakarta Mail code works on your laptop but times out on a cloud server sending to port 25. What's the likely cause and fix?
Many cloud providers and ISPs block outgoing port 25 to fight spam. Submit through your mail provider or a transactional mail service on port 587 (STARTTLS) or 465 (implicit TLS) with authentication, instead of port 25. Also set mail.smtp.connectiontimeout and mail.smtp.timeout so failures are reported quickly.
Previous: A Simple HTTP Server in Java: jwebserver, HttpServer, Handlers and Filters
Next: JDBC Design and SQL Basics: How Java Talks to Databases
Related reading
- A Simple HTTP Server in Java: jwebserver, HttpServer, Handlers and Filters
- Asynchronous HTTP and WebSocket in Java: sendAsync, HTTP/2 and WebSocket
- The Java HttpClient: Requests, Responses, Body Publishers and Handlers
- Posting Form Data in Java: GET and POST, URL Encoding and Multipart
- URIs, URLs and URLConnection in Java: Retrieving Web Data and Headers

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.