Apache Camel Mail component: sending and receiving email

The Mail component sends messages over SMTP and reads mailboxes over POP3 or IMAP, using Jakarta Mail underneath. In Camel 4.23 the endpoint, not the message headers, decides who receives a mail by default. This page explains how sending and polling work, then runs each important case against a small mail server started inside the program.

Contents

How the Mail component sends and receives email

The Mail component, in camel-mail, connects routes to mail servers through Jakarta Mail. Camel 4.23 uses the Jakarta Mail 2.1 API with Eclipse Angus Mail 2.0 as the implementation. One component serves six URI schemes:

Mail URI schemes and their default ports
SchemeProtocolDirectionDefault port
smtpSMTP, plain or upgraded with STARTTLSSend25
smtpsSMTP over TLS from the first byteSend465
pop3, pop3sPOP3: download from one mailboxReceive110, 995
imap, imapsIMAP: folders, flags, server-side searchReceive143, 993

As a producer, the component builds a MimeMessage from the exchange: the body becomes the text, the endpoint options give sender, recipients and subject, attachments become MIME parts, and most other message headers become mail headers. It then opens an SMTP connection, logs in if a user name is set, and hands the message to the server. As a consumer, it is a scheduled poller: every delay milliseconds (60000 by default) it opens the folder, fetches the messages, by default only unseen ones, turns each into an exchange, and afterwards marks it seen or deleted.

The examples need a mail server, and none is available where they were run. They use MailStub, shown in the next section: a small SMTP and POP3 server written for this page, which runs inside each program. It accepts any login, has no TLS, and implements only the commands that Jakarta Mail sends. The SMTP and POP3 conversations in the examples are real, but IMAP, TLS and a real provider were not run; the sections on those show configuration only, checked against the component's option catalog. The programs use Camel 4.23 on Java 21 with Camel's logging turned off.

A local mail server for the examples

SMTP and POP3 are line-based text protocols, so a server that answers the commands a client sends fits in one class. This one stores each message it receives as raw text, so the programs can print exactly what Camel sent, and serves the stored messages back over POP3:

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CopyOnWriteArrayList;

// A tiny in-memory mail server for the examples: SMTP to receive, POP3 to read back.
// It accepts any login and implements only the commands the Jakarta Mail client uses.
public class MailStub implements AutoCloseable {

    public record Mail(String from, List<String> to, String data) {}

    public final List<Mail> inbox = new CopyOnWriteArrayList<>();
    public final List<String> log = new CopyOnWriteArrayList<>();
    private final ServerSocket smtp;
    private final ServerSocket pop3;

    public MailStub() throws IOException {
        InetAddress local = InetAddress.getLoopbackAddress();
        smtp = new ServerSocket(0, 10, local);
        pop3 = new ServerSocket(0, 10, local);
        Thread.ofVirtual().start(() -> serve(smtp, true));
        Thread.ofVirtual().start(() -> serve(pop3, false));
    }

    public int smtpPort() {
        return smtp.getLocalPort();
    }

    public int pop3Port() {
        return pop3.getLocalPort();
    }

    private void serve(ServerSocket server, boolean isSmtp) {
        while (!server.isClosed()) {
            try (Socket s = server.accept();
                    var in = new BufferedReader(new InputStreamReader(s.getInputStream(),
                            StandardCharsets.UTF_8));
                    var out = new PrintWriter(s.getOutputStream(), true,
                            StandardCharsets.UTF_8)) {
                if (isSmtp) {
                    smtpSession(in, out);
                } else {
                    pop3Session(in, out);
                }
            } catch (IOException e) {
                // socket closed by close(): stop serving
            }
        }
    }

    private void smtpSession(BufferedReader in, PrintWriter out) throws IOException {
        out.print("220 stub ESMTP\r\n");
        out.flush();
        String from = null;
        List<String> to = new ArrayList<>();
        for (String line; (line = in.readLine()) != null; ) {
            String cmd = line.toUpperCase();
            if (cmd.startsWith("EHLO")) {
                out.print("250-stub\r\n250 AUTH PLAIN\r\n");
            } else if (cmd.startsWith("AUTH PLAIN ")) {
                String[] parts = new String(Base64.getDecoder().decode(line.substring(11)),
                        StandardCharsets.UTF_8).split("\0");
                log.add("AUTH PLAIN user=" + parts[1] + " password=" + parts[2]);
                out.print("235 accepted\r\n");
            } else if (cmd.startsWith("MAIL FROM:")) {
                from = line.substring(10).replaceAll("[<>]", "").strip();
                out.print("250 ok\r\n");
            } else if (cmd.startsWith("RCPT TO:")) {
                String rcpt = line.substring(8).replaceAll("[<>]", "").strip();
                if (rcpt.startsWith("nobody@")) {
                    out.print("550 no such user " + rcpt + "\r\n");
                } else {
                    to.add(rcpt);
                    out.print("250 ok\r\n");
                }
            } else if (cmd.equals("DATA")) {
                out.print("354 end with .\r\n");
                out.flush();
                StringBuilder data = new StringBuilder();
                for (String d; !(d = in.readLine()).equals("."); ) {
                    data.append(d.startsWith("..") ? d.substring(1) : d).append("\r\n");
                }
                inbox.add(new Mail(from, List.copyOf(to), data.toString()));
                to.clear();
                out.print("250 queued\r\n");
            } else if (cmd.equals("QUIT")) {
                out.print("221 bye\r\n");
                out.flush();
                return;
            } else {
                out.print("250 ok\r\n");
            }
            out.flush();
        }
    }

    private void pop3Session(BufferedReader in, PrintWriter out) throws IOException {
        out.print("+OK stub POP3\r\n");
        out.flush();
        Set<Integer> deleted = new TreeSet<>();
        List<Mail> mails = List.copyOf(inbox);
        for (String line; (line = in.readLine()) != null; ) {
            String[] cmd = line.split(" ");
            switch (cmd[0].toUpperCase()) {
                case "CAPA" -> out.print("+OK\r\nUSER\r\nUIDL\r\nTOP\r\n.\r\n");
                case "STAT" -> out.print("+OK " + mails.size() + " "
                        + mails.stream().mapToInt(m -> m.data().length()).sum() + "\r\n");
                case "LIST" -> {
                    out.print("+OK\r\n");
                    for (int i = 0; i < mails.size(); i++) {
                        out.print((i + 1) + " " + mails.get(i).data().length() + "\r\n");
                    }
                    out.print(".\r\n");
                }
                case "UIDL" -> {
                    out.print("+OK\r\n");
                    for (int i = 0; i < mails.size(); i++) {
                        out.print((i + 1) + " uid-" + (i + 1) + "\r\n");
                    }
                    out.print(".\r\n");
                }
                case "RETR", "TOP" -> {
                    String data = mails.get(Integer.parseInt(cmd[1]) - 1).data();
                    if (cmd[0].equalsIgnoreCase("TOP")) {
                        data = data.substring(0, data.indexOf("\r\n\r\n") + 4);
                    }
                    out.print("+OK\r\n" + data.replace("\r\n.", "\r\n..") + ".\r\n");
                }
                case "DELE" -> {
                    deleted.add(Integer.parseInt(cmd[1]));
                    out.print("+OK\r\n");
                }
                case "QUIT" -> {
                    for (int n : deleted) {
                        inbox.remove(mails.get(n - 1));
                    }
                    log.add("POP3 QUIT, deleted messages " + deleted);
                    out.print("+OK bye\r\n");
                    out.flush();
                    return;
                }
                default -> out.print("+OK\r\n");
            }
            out.flush();
        }
    }

    @Override
    public void close() throws IOException {
        smtp.close();
        pop3.close();
    }
}
  • The SMTP side advertises AUTH PLAIN, decodes the login and records it in log, rejects any recipient starting with nobody@ with a 550 reply, and stores the envelope sender, the recipients and the message text.
  • The POP3 side lists, retrieves and deletes the stored messages. Deletions take effect at QUIT, as the protocol requires.
  • Both listen on a free port on the loopback address, chosen by the operating system, and run on virtual threads.

For tests in your own projects, a maintained test server such as GreenMail does the same job with full protocol support.

Sending a first email

An order notification needs a subject built from the order, a fixed sender and a fixed recipient. The program prints the login the server received, the SMTP envelope, and the message text:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class FirstMail {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (MailStub server = new MailStub()) {
            String smtp = "smtp://localhost:" + server.smtpPort();
            CamelContext context = new DefaultCamelContext();
            context.addRoutes(new RouteBuilder() {
                @Override
                public void configure() {
                    from("direct:notify")
                            .setHeader("Subject", simple("Order ${header.orderId} shipped"))
                            .to(smtp + "?username=shop&password=s3cret"
                                    + "&from=shop@example.com&to=alice@example.com"
                                    + "&useHeaderSubject=true");
                }
            });
            context.start();
            ProducerTemplate template = context.createProducerTemplate();
            template.sendBodyAndHeaders("direct:notify",
                    "Hello Alice,\nyour order is on its way.", Map.of("orderId", 1042));
            context.close();

            System.out.println("Server log: " + server.log);
            MailStub.Mail mail = server.inbox.get(0);
            System.out.println("Envelope: MAIL FROM " + mail.from() + ", RCPT TO " + mail.to());
            System.out.println("Message as sent (Date and Message-ID lines left out):");
            for (String line : mail.data().split("\r\n")) {
                if (!line.startsWith("Date:") && !line.startsWith("Message-ID:")) {
                    System.out.println("  " + line);
                }
            }
        }
    }
}
Output
Server log: [AUTH PLAIN user=shop password=s3cret]
Envelope: MAIL FROM shop@example.com, RCPT TO [alice@example.com]
Message as sent (Date and Message-ID lines left out):
  From: shop@example.com
  To: alice@example.com
  Subject: Order 1042 shipped
  MIME-Version: 1.0
  Content-Type: text/plain
  Content-Transfer-Encoding: 7bit
  orderId: 1042
  
  Hello Alice,
  your order is on its way.
  • Because the endpoint has username and password, the client logged in with AUTH PLAIN, and the server decoded shop and s3cret. PLAIN is only Base64, not encryption: anyone who can read the connection can read the password. Use it only over TLS, as a later section shows.
  • The envelope, the MAIL FROM and RCPT TO commands, came from the from and to options. Servers deliver by the envelope, not by the To: line in the text.
  • The Subject header set in the route became Subject: Order 1042 shipped, because the endpoint has useHeaderSubject=true. The next section shows why that option is needed.
  • The plain-text body was sent as text/plain with 7-bit encoding, since it is plain ASCII.
  • The header orderId: 1042 also ended up in the mail. Every message header that is not filtered becomes a mail header, visible to the recipient in the raw message.

The program leaves out the Date and Message-ID lines, which differ on every run.

Which message headers may change the mail

A route that sends mail often handles messages from outside: an HTTP request, a queue message, a parsed file. If headers from such a message could set the recipient or the subject, anyone who can send to the route could use it to send mail to anyone. In Camel 4.23 the endpoint's options win by default. This program sends the same message, with untrusted Subject, To and trackingCode headers, through four endpoints:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.support.DefaultHeaderFilterStrategy;
import org.slf4j.LoggerFactory;

public class HeaderRules {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (MailStub server = new MailStub()) {
            CamelContext context = new DefaultCamelContext();
            context.start();
            ProducerTemplate template = context.createProducerTemplate();
            String smtp = "smtp://localhost:" + server.smtpPort()
                    + "?from=shop@example.com&to=orders@example.com&subject=New order";
            // headers as they might arrive from an HTTP request or a queue message
            Map<String, Object> headers = Map.of(
                    "Subject", "URGENT: reset your password",
                    "To", "victim@example.org",
                    "trackingCode", "TR-778");

            String[] options = {"", "&useHeaderSubject=true",
                "&useHeaderRecipients=true", "&headerFilterStrategy=#dropAll"};
            DefaultHeaderFilterStrategy dropAll = new DefaultHeaderFilterStrategy();
            dropAll.setOutFilterStartsWith(""); // every name starts with ""
            context.getRegistry().bind("dropAll", dropAll);
            for (String option : options) {
                server.inbox.clear();
                template.sendBodyAndHeaders(smtp + option, "2 x book", headers);
                MailStub.Mail mail = server.inbox.get(0);
                System.out.println(option.isEmpty() ? "defaults:" : option.substring(1) + ":");
                System.out.println("  RCPT TO " + mail.to());
                mail.data().lines()
                        .filter(l -> l.startsWith("Subject:") || l.startsWith("trackingCode:"))
                        .forEach(l -> System.out.println("  " + l));
            }
            context.close();
        }
    }
}
Output
defaults:
  RCPT TO [orders@example.com]
  Subject: New order
  trackingCode: TR-778
useHeaderSubject=true:
  RCPT TO [orders@example.com]
  Subject: URGENT: reset your password
  trackingCode: TR-778
useHeaderRecipients=true:
  RCPT TO [victim@example.org]
  Subject: New order
  trackingCode: TR-778
headerFilterStrategy=#dropAll:
  RCPT TO [orders@example.com]
  Subject: New order
  • With the defaults, the mail went to orders@example.com with the subject New order, both from the endpoint. The Subject and To headers were ignored.
  • useHeaderSubject=true let the header replace the subject, so the mail said URGENT: reset your password.
  • useHeaderRecipients=true let the To header replace the recipient, and the mail went to victim@example.org. This is the setting to keep off unless the route itself sets the header.
  • In every case except the last, trackingCode: TR-778 went out as a mail header. A DefaultHeaderFilterStrategy that filters every outgoing name removed it. In a route, removeHeaders("*") before the mail endpoint does the same.

Similar options exist for the sender, useHeaderFrom, and for Reply-To, useHeaderReplyTo, all false by default. Many older examples set the Subject or To header and expect it to work; with Camel 4.23 they need the matching option. When a route must choose the recipient at runtime, compute it in the route, check it, and then enable useHeaderRecipients.

HTML, a plain-text alternative and attachments

An invoice email usually has an HTML body, a plain-text version for clients that do not show HTML, and a file. The program sends all three, including a euro sign so that the character set matters, then parses the raw message with Jakarta Mail and prints its MIME structure:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import jakarta.activation.DataHandler;
import jakarta.mail.BodyPart;
import jakarta.mail.Multipart;
import jakarta.mail.Part;
import jakarta.mail.Session;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.util.ByteArrayDataSource;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.attachment.AttachmentMessage;
import org.apache.camel.component.mail.MailConstants;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class HtmlAttachments {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (MailStub server = new MailStub()) {
            CamelContext context = new DefaultCamelContext();
            context.start();
            ProducerTemplate template = context.createProducerTemplate();
            String smtp = "smtp://localhost:" + server.smtpPort()
                    + "?from=billing@example.com&to=alice@example.com"
                    + "&subject=Your invoice&contentType=text/html; charset=UTF-8";

            template.send(smtp, exchange -> {
                AttachmentMessage message = exchange.getIn(AttachmentMessage.class);
                message.setBody("<h1>Invoice 77</h1><p>Total: <b>12,50 €</b></p>");
                message.setHeader(MailConstants.MAIL_ALTERNATIVE_BODY,
                        "Invoice 77\nTotal: 12,50 €");
                message.addAttachment("invoice-77.csv", new DataHandler(new ByteArrayDataSource(
                        "item,price\nbook,12.50\n".getBytes(StandardCharsets.UTF_8),
                        "text/csv")));
            });
            context.close();

            byte[] raw = server.inbox.get(0).data().getBytes(StandardCharsets.UTF_8);
            MimeMessage mail = new MimeMessage(Session.getInstance(new Properties()),
                    new ByteArrayInputStream(raw));
            System.out.println("Subject: " + mail.getSubject());
            print(mail, "");
        }
    }

    // prints the MIME tree: one line per part, children indented
    static void print(Part part, String indent) throws Exception {
        String type = part.getContentType().replaceAll("\\s+", " ")
                .replaceAll("boundary=\"[^\"]*\"", "boundary=...");
        String name = part.getFileName() == null ? "" : ", file " + part.getFileName();
        System.out.println(indent + type + name);
        if (part.getContent() instanceof Multipart multipart) {
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart child = multipart.getBodyPart(i);
                print(child, indent + "  ");
            }
        } else if (part.getContent() instanceof String text) {
            String shown = part.isMimeType("text/html")
                    ? "(tags removed) " + text.replaceAll("<[^>]+>", " ").strip()
                    : text.strip();
            System.out.println(indent + "  | " + shown.replaceAll("\\R", " / ")
                    .replaceAll(" +", " "));
        }
    }
}
Output
Subject: Your invoice
multipart/alternative; boundary=...
  text/plain; charset=UTF-8
    | Invoice 77 / Total: 12,50 €
  multipart/mixed; boundary=...
    text/html; charset=UTF-8
      | (tags removed) Invoice 77 Total: 12,50 €
    text/csv; charset=us-ascii; name=invoice-77.csv, file invoice-77.csv
  • contentType=text/html; charset=UTF-8 made the body an HTML part in UTF-8, and the € survived. The program strips the tags when it prints the HTML part. Without the charset, non-ASCII characters can arrive garbled.
  • The CamelMailAlternativeBody header created a multipart/alternative message whose first part is the plain-text version. Mail clients show the last alternative they can display, so HTML clients show the HTML.
  • The attachment went into a multipart/mixed part together with the HTML, inside the alternative. A client that shows only the plain-text alternative may not show the attachment at all. If every reader must get the file, send it without an alternative body.
  • The CSV attachment kept its file name, invoice-77.csv, and its type, text/csv.

Attachments are added through AttachmentMessage, from camel-attachments, which camel-mail depends on. exchange.getIn(AttachmentMessage.class) returns the same message with the attachment methods available.

When sending fails

SMTP servers check recipients one by one, so a message with several recipients can fail for only some of them. The program sends to one good and one unknown address, then tries a port with nothing listening:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import jakarta.mail.Address;
import jakarta.mail.SendFailedException;
import java.net.ServerSocket;
import java.util.Arrays;
import org.apache.camel.CamelContext;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class SendFailure {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (MailStub server = new MailStub()) {
            CamelContext context = new DefaultCamelContext();
            context.start();
            ProducerTemplate template = context.createProducerTemplate();
            String smtp = "smtp://localhost:" + server.smtpPort() + "?subject=Report";

            System.out.println("One recipient rejected by the server:");
            try {
                template.sendBody(smtp + "&to=alice@example.com,nobody@example.com", "report");
            } catch (CamelExecutionException e) {
                SendFailedException failed = (SendFailedException) e.getCause();
                System.out.println("  " + failed.getClass().getSimpleName() + ": "
                        + failed.getMessage());
                System.out.println("  valid but unsent: "
                        + names(failed.getValidUnsentAddresses()));
                System.out.println("  invalid: " + names(failed.getInvalidAddresses()));
            }
            System.out.println("  messages the server accepted: " + server.inbox.size());

            System.out.println("Nothing listening on the port:");
            int closedPort;
            try (ServerSocket probe = new ServerSocket(0)) {
                closedPort = probe.getLocalPort();
            }
            try {
                template.sendBody("smtp://localhost:" + closedPort
                        + "?to=alice@example.com&connectionTimeout=2000", "report");
            } catch (CamelExecutionException e) {
                Throwable cause = e.getCause();
                System.out.println("  " + cause.getClass().getName() + ": "
                        + cause.getMessage().lines().findFirst().orElse("")
                                .replace(String.valueOf(closedPort), "PORT"));
            }
            context.close();
        }
    }

    static String names(Address[] addresses) {
        return addresses == null ? "[]" : Arrays.toString(addresses);
    }
}
Output
One recipient rejected by the server:
  SendFailedException: Invalid Addresses
  valid but unsent: [alice@example.com]
  invalid: [nobody@example.com]
  messages the server accepted: 0
Nothing listening on the port:
  org.eclipse.angus.mail.util.MailConnectException: Couldn't connect to host, port: localhost, PORT; timeout 2000
  • The server rejected nobody@example.com with 550. Jakarta Mail threw SendFailedException and sent nothing, not even to alice@example.com, which it listed as valid but unsent. The server accepted no messages.
  • getInvalidAddresses() named the rejected address, so an error handler can remove it and try again, or report it.
  • With no server on the port, the client failed with Angus Mail's MailConnectException. connectionTimeout=2000 limits how long a connection attempt may take; the default is 30 seconds.

To deliver to the valid recipients even when others are rejected, Jakarta Mail has the property mail.smtp.sendpartial=true. Mail sending is a good candidate for redelivery with a delay, since servers are often briefly unavailable, but a rejected address will never succeed, so retry connection failures only. See Camel error handling for redelivery policies.

Receiving mail with POP3 and IMAP

A support mailbox is the usual reason to receive mail in a route. The program sends two messages, one with an attachment, through the stub's SMTP side, and then starts a route that polls the POP3 side and deletes what it has read:

Java
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import jakarta.activation.DataHandler;
import jakarta.mail.util.ByteArrayDataSource;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.attachment.AttachmentMessage;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.slf4j.LoggerFactory;

public class Pop3Receive {

    public static void main(String[] args) throws Exception {
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        try (MailStub server = new MailStub()) {
            CamelContext context = new DefaultCamelContext();
            context.start();
            ProducerTemplate template = context.createProducerTemplate();
            String smtp = "smtp://localhost:" + server.smtpPort() + "?to=support@example.com";
            template.sendBody(smtp + "&from=bob@example.com&subject=Login fails",
                    "I cannot log in since Monday.");
            template.send(smtp + "&from=carol@example.com&subject=Broken item", exchange -> {
                AttachmentMessage message = exchange.getIn(AttachmentMessage.class);
                message.setBody("The lamp arrived broken, photo attached.");
                message.addAttachment("lamp.jpg", new DataHandler(new ByteArrayDataSource(
                        "not really a photo".getBytes(StandardCharsets.UTF_8), "image/jpeg")));
            });
            System.out.println("messages waiting on the server: " + server.inbox.size());

            // the polling route is added only now, after both mails were sent
            NotifyBuilder twoRead = new NotifyBuilder(context).fromRoute("support-inbox")
                    .whenDone(2).create();
            context.addRoutes(new RouteBuilder() {
                @Override
                public void configure() {
                    from("pop3://localhost:" + server.pop3Port()
                            + "?username=support&password=secret"
                            + "&delete=true&initialDelay=0&delay=500")
                            .routeId("support-inbox")
                            .process(exchange -> {
                                AttachmentMessage in = exchange.getIn(AttachmentMessage.class);
                                System.out.println("From " + in.getHeader("From")
                                        + ", Subject '" + in.getHeader("Subject") + "'");
                                System.out.println("  body: " + in.getBody(String.class).strip()
                                        + " (" + in.getBody().getClass().getSimpleName() + ")");
                                if (in.hasAttachments()) {
                                    System.out.println("  attachments: "
                                            + in.getAttachmentNames());
                                }
                            });
                }
            });
            System.out.println("both read: " + twoRead.matches(10, TimeUnit.SECONDS));
            context.close();
            server.log.stream().filter(line -> !line.endsWith("[]"))
                    .forEach(line -> System.out.println("server log: " + line));
            System.out.println("messages left on the server: " + server.inbox.size());
        }
    }
}
Output
messages waiting on the server: 2
From bob@example.com, Subject 'Login fails'
  body: I cannot log in since Monday. (String)
From carol@example.com, Subject 'Broken item'
  body: The lamp arrived broken, photo attached. (MimeMultipart)
  attachments: [lamp.jpg]
both read: true
server log: POP3 QUIT, deleted messages [1, 2]
messages left on the server: 0
  • Each message became one exchange, with From and Subject as headers. All mail headers are mapped to message headers this way, because mapMailMessage is true by default.
  • The first body was a String. The second was a MimeMultipart, because the message had an attachment, but getBody(String.class) still returned the text part, and the attachment arrived as lamp.jpg in the attachment map.
  • delete=true made the consumer delete both messages, and the server applied the deletions when the client sent QUIT. Without delete, Camel marks messages as seen instead. POP3 has no seen flag on the server, so a POP3 route without delete=true reads the same messages again on the next poll.

IMAP keeps flags and folders on the server, which makes it the better choice for routes. This configuration was not run here, since no IMAP server was available; the options and defaults come from the component's catalog:

Java
from("imaps://imap.example.com?username=support@example.com&password={{mail.password}}"
        + "&unseen=true&delete=false&moveTo=Processed&delay=30000")
        .to("direct:createTicket");
  • unseen=true, the default, fetches only messages without the seen flag.
  • peek=true, also the default, reads IMAP messages without marking them seen, so that a failed exchange leaves the message unread for the next poll.
  • moveTo=Processed moves each processed message to another folder, which keeps the inbox small and makes reprocessing easy.
  • searchTerm filters on the server, for example by subject or sender, and idempotentRepository stops two Camel instances from processing the same message.

Real servers: TLS and providers

Real mail providers require TLS and authentication. There are two ways to use TLS with SMTP, and they use different ports. These settings were not run here; the option names come from the camel-mail catalog, and the mail.* properties from Jakarta Mail:

Java
// implicit TLS: the connection starts encrypted, usually on port 465
from("direct:receipts")
        .to("smtps://smtp.example.com:465?username=app@example.com&password=RAW(app-password)");

// STARTTLS: connect in plain text on port 587, then upgrade before logging in
from("direct:alerts")
        .to("smtp://smtp.example.com:587?username=app@example.com&password=RAW(app-password)"
                + "&mail.smtp.starttls.enable=true&mail.smtp.starttls.required=true");
  • Options that start with mail. are passed to Jakarta Mail as session properties; that is the additionalJavaMailProperties option. mail.smtp.starttls.required=true makes the connection fail rather than send the password unencrypted when the server does not offer STARTTLS.
  • RAW(...) stops Camel from interpreting characters such as + or & in a password. Better still, keep the password out of the URI with a property placeholder such as {{mail.password}}.
  • Gmail does not accept the normal account password for SMTP: it needs an app password or OAuth 2.0, and other large providers are moving the same way. For tokens that expire, set authenticator to a MailAuthenticator that returns the current token.
  • For a private CA, set sslContextParameters, as with HTTP; see the HTTPS section of the Camel HTTP component page.

In Spring Boot with camel-mail-starter, the same options can be set for all endpoints under camel.component.mail.*, as the Camel with Spring Boot page shows for other components.

Choosing mail options

Common situations and the options that fit them
SituationOptions
Notifications to fixed recipientsto, from and subject on the endpoint, and removeHeaders("*") before it
Subject built in the routeuseHeaderSubject=true
Recipient chosen at runtimeuseHeaderRecipients=true, with the address set and checked by the route
HTML mailcontentType=text/html; charset=UTF-8, plus CamelMailAlternativeBody for a text version
FilesAttachmentMessage.addAttachment
Sending through a providersmtps on 465, or smtp on 587 with mail.smtp.starttls.required=true
Reading a mailboximaps with moveTo; pop3s only with delete=true
Several instances reading one mailboxidempotentRepository
Slow or unreachable serversconnectionTimeout and redelivery for connection errors

The traps to remember are headers that become mail headers, the useHeader* options that keep message headers from choosing recipients and subjects, attachments that hide inside the HTML alternative, and POP3 routes that read the same messages again because nothing deletes them.