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 A local mail server for the examples Sending a first email Which message headers may change the mail HTML, a plain-text alternative and attachments When sending fails Receiving mail with POP3 and IMAP Real servers: TLS and providers Choosing mail options
How the Mail component sends and receives email
The Mail component, in camel-mail
| Scheme | Protocol | Direction | Default port |
|---|---|---|---|
smtp | SMTP, plain or upgraded with STARTTLS | Send | 25 |
smtps | SMTP over TLS from the first byte | Send | 465 |
pop3pop3s | POP3: download from one mailbox | Receive | 110, 995 |
imapimaps | IMAP: folders, flags, server-side search | Receive | 143, 993 |
As a producer, the component builds a MimeMessagedelay
The examples need a mail server, and none is available where they were run. They use MailStub
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:
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
, decodes the login and records it inAUTH PLAIN , rejects any recipient starting withlog with anobody@ reply, and stores the envelope sender, the recipients and the message text.550 - The POP3 side lists, retrieves and deletes the stored messages. Deletions take effect at
, as the protocol requires.QUIT - 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:
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);
}
}
}
}
}
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
andusername , the client logged in withpassword , and the server decodedAUTH PLAIN andshop . 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.s3cret - The envelope, the
andMAIL FROM commands, came from theRCPT TO andfrom options. Servers deliver by the envelope, not by theto line in the text.To: - The
header set in the route becameSubject , because the endpoint hasSubject: Order 1042 shipped . The next section shows why that option is needed.useHeaderSubject=true - The plain-text body was sent as
with 7-bit encoding, since it is plain ASCII.text/plain - The header
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.orderId: 1042
The program leaves out the DateMessage-ID
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 SubjectTotrackingCode
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();
}
}
}
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
with the subjectorders@example.com , both from the endpoint. TheNew order andSubject headers were ignored.To let the header replace the subject, so the mail saiduseHeaderSubject=true .URGENT: reset your password let theuseHeaderRecipients=true header replace the recipient, and the mail went toTo . This is the setting to keep off unless the route itself sets the header.victim@example.org- In every case except the last,
went out as a mail header. AtrackingCode: TR-778 that filters every outgoing name removed it. In a route,DefaultHeaderFilterStrategy before the mail endpoint does the same.removeHeaders("*")
Similar options exist for the sender, useHeaderFromReply-TouseHeaderReplyTofalseSubjectTouseHeaderRecipients
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:
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(" +", " "));
}
}
}
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
made the body an HTML part in UTF-8, and thecontentType=text/html; charset=UTF-8 survived. The program strips the tags when it prints the HTML part. Without the charset, non-ASCII characters can arrive garbled.€- The
header created aCamelMailAlternativeBody message whose first part is the plain-text version. Mail clients show the last alternative they can display, so HTML clients show the HTML.multipart/alternative - The attachment went into a
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.multipart/mixed - The CSV attachment kept its file name,
, and its type,invoice-77.csv .text/csv
Attachments are added through AttachmentMessagecamel-attachmentscamel-mailexchange.getIn(AttachmentMessage.class)
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:
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);
}
}
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
withnobody@example.com . Jakarta Mail threw550 and sent nothing, not even toSendFailedException , which it listed as valid but unsent. The server accepted no messages.alice@example.com named the rejected address, so an error handler can remove it and try again, or report it.getInvalidAddresses()- With no server on the port, the client failed with Angus Mail's
.MailConnectException limits how long a connection attempt may take; the default is 30 seconds.connectionTimeout=2000
To deliver to the valid recipients even when others are rejected, Jakarta Mail has the property mail.smtp.sendpartial=true
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:
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());
}
}
}
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
andFrom as headers. All mail headers are mapped to message headers this way, becauseSubject ismapMailMessage by default.true - The first body was a
. The second was aString , because the message had an attachment, butMimeMultipart still returned the text part, and the attachment arrived asgetBody(String.class) in the attachment map.lamp.jpg made the consumer delete both messages, and the server applied the deletions when the client sentdelete=true . WithoutQUIT , Camel marks messages as seen instead. POP3 has no seen flag on the server, so a POP3 route withoutdelete reads the same messages again on the next poll.delete=true
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:
from("imaps://imap.example.com?username=support@example.com&password={{mail.password}}"
+ "&unseen=true&delete=false&moveTo=Processed&delay=30000")
.to("direct:createTicket");
, the default, fetches only messages without the seen flag.unseen=true , also the default, reads IMAP messages without marking them seen, so that a failed exchange leaves the message unread for the next poll.peek=true moves each processed message to another folder, which keeps the inbox small and makes reprocessing easy.moveTo=Processed filters on the server, for example by subject or sender, andsearchTerm stops two Camel instances from processing the same message.idempotentRepository
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-mailmail.*
// 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
are passed to Jakarta Mail as session properties; that is themail. option.additionalJavaMailProperties makes the connection fail rather than send the password unencrypted when the server does not offer STARTTLS.mail.smtp.starttls.required=true stops Camel from interpreting characters such asRAW(...) 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
to aauthenticator that returns the current token.MailAuthenticator - For a private CA, set
, as with HTTP; see the HTTPS section of thesslContextParametersCamel HTTP component page.
In Spring Boot with camel-mail-startercamel.component.mail.*
Choosing mail options
| Situation | Options |
|---|---|
| Notifications to fixed recipients | tofromsubjectremoveHeaders("*") |
| Subject built in the route | useHeaderSubject=true |
| Recipient chosen at runtime | useHeaderRecipients=true |
| HTML mail | contentType=text/html; charset=UTF-8CamelMailAlternativeBody |
| Files | AttachmentMessage.addAttachment |
| Sending through a provider | smtpssmtpmail.smtp.starttls.required=true |
| Reading a mailbox | imapsmoveTopop3sdelete=true |
| Several instances reading one mailbox | idempotentRepository |
| Slow or unreachable servers | connectionTimeout |
The traps to remember are headers that become mail headers, the useHeader*