Camel Components

Mail

Since Camel 1.0

Both producer and consumer are supported

The Mail component sends and receives emails with Jakarta Mail (Eclipse Angus Mail).

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-mail</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

POP3 or IMAP

POP3 has some limitations and end users are encouraged to use IMAP if possible.

Using mock-mail for testing

You can use a mock framework for unit testing, which allows you to test without the need for a real mail server. However, you should remember to not include the mock-mail when you go into production or other environments where you need to send mail to a real mail server. Just the presence of the mock-javamail.jar on the classpath means that it will kick in and avoid sending the mails.

URI format

Mail endpoints can have one of the following URI formats (for the protocols, SMTP, POP3, or IMAP, respectively):

smtp://[username@]host[:port][?options]
pop3://[username@]host[:port][?options]
imap://[username@]host[:port][?options]

The mail component also supports secure variants of these protocols (layered over SSL). You can enable the secure protocols by adding s to the scheme:

smtps://[username@]host[:port][?options]
pop3s://[username@]host[:port][?options]
imaps://[username@]host[:port][?options]

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Mail component supports the following options which are listed below.

Name Description Default Type

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

closeFolder (consumer)

Whether the consumer closes the folder after each poll. Closing expunges the mails flagged DELETED (by delete or moveTo). With closeFolder=false and disconnect=false the folder stays open between polls, and deleted mails are removed only when the folder is closed, at the latest when the consumer stops. Keep it true for POP3: a POP3 folder that stays open does not see new mails.

true

boolean

copyTo (consumer)

The IMAP folder to copy a mail to once its exchange completed successfully. The folder is created if it does not exist. The CamelMailCopyTo header overrides this option for a mail. Ignored for POP3.

String

decodeFilename (consumer)

Whether the consumer decodes MIME encoded file names of attachments with MimeUtility.decodeText. This is like setting the system property mail.mime.decodefilename=true.

false

boolean

delete (consumer)

Whether the consumer deletes a mail once its exchange completed successfully: it sets the DELETED flag on the mail instead of the SEEN flag, and the mail is removed from the server when the folder is closed (see closeFolder). The CamelMailDelete header overrides this option for a mail. POP3 keeps no SEEN flag on the server, so with POP3 deleting is how a consumed mail is not consumed again.

false

boolean

disconnect (consumer)

Whether the consumer closes the folder and disconnects from the mail server (Store.close) after each poll, so that every poll connects again. By default the connection stays open between polls.

false

boolean

handleFailedMessage (consumer)

Whether the consumer passes the exception of a mail that it cannot retrieve or map to an exchange to its exception handler (which logs it at WARN, or with bridgeErrorHandler=true routes it to the error handler of the route), and goes on with the next mail. When neither this option nor skipFailedMessage is set, the poll fails and none of its mails is routed.

false

boolean

mimeDecodeHeaders (consumer)

Whether the consumer unfolds the mail header values and decodes their MIME encoded words (MimeUtility.decodeText, for example =?UTF-8?B?…​?=) before it maps them to Camel headers.

false

boolean

moveTo (consumer)

The IMAP folder to move a mail to once its exchange completed successfully: the mail is copied to that folder and flagged DELETED in the polled folder, from which it is removed when the folder is closed (see closeFolder). The folder is created if it does not exist. The CamelMailMoveTo header overrides this option for a mail. Ignored for POP3.

String

peek (consumer)

Whether the consumer sets peek on each IMAP mail (IMAPMessage.setPeek) before reading it, so reading the mail does not set the SEEN flag on the server. The consumer then sets SEEN (or DELETED) only once the exchange completed successfully, so a mail whose exchange failed stays unseen and a later poll consumes it again. With peek=false the server sets SEEN when the content is read, which with mapMailMessage=true happens for every mail of a poll when it is retrieved: a mail that fails or is not routed (the consumer stops, or an earlier mail of the poll failed) is then not polled again with unseen=true. IMAP only.

true

boolean

skipFailedMessage (consumer)

Whether the consumer skips a mail that it cannot retrieve or map to an exchange (for example a malformed mail), logging it at DEBUG, and goes on with the next mail. When neither this option nor handleFailedMessage is set, the poll fails and none of its mails is routed. Takes precedence over handleFailedMessage.

false

boolean

unseen (consumer)

Whether the consumer polls only the mails that do not have the SEEN flag. Ignored when a searchTerm is set. POP3 keeps no flags on the server, so every mail counts as unseen each time the folder is opened: use delete=true, or an idempotentRepository with idempotentRepositoryRemoveOnCommit=false, to not consume a mail again.

true

boolean

failOnDuplicateFileAttachment (consumer (advanced))

Whether to fail processing the mail if the mail message contains attachments with duplicate file names. If set to false, then the duplicate attachment is skipped and a WARN is logged. If set to true, then an exception is thrown failing to process the mail message.

false

boolean

fetchSize (consumer (advanced))

The maximum number of mails the consumer consumes per poll, which avoids loading the mail server when a folder holds many mails. -1 (default) sets no limit here, so maxMessagesPerPoll applies. 0 skips every poll, so no mail is consumed. A value of 0 or more takes precedence over maxMessagesPerPoll.

-1

int

folderName (consumer (advanced))

The name of the folder the consumer polls. With POP3, only INBOX exists.

INBOX

String

generateMissingAttachmentNames (consumer (advanced))

How the consumer names an attachment (a part with the Content-Disposition attachment or inline) that has no file name: never (default) leaves it without a name, so it is not extracted as an attachment; uuid names it with a random UUID.

String

handleDuplicateAttachmentNames (consumer (advanced))

How the consumer handles attachments of a mail that have the same file name: never (default) keeps the first one and skips the others, or fails with failOnDuplicateFileAttachment=true; uuidPrefix renames them to uuid_filename.ext; uuidSuffix renames them to filename_uuid.ext.

String

mapMailMessage (consumer (advanced))

Whether the consumer maps the mail to the Camel message: the content of the mail becomes the body (a String for a text mail, a Multipart for a multipart mail) and the attachments become Camel attachments, all read from the server when the mail is polled. When false, the body is the jakarta.mail.Message itself, no attachments are extracted, and the content is read only when the route reads it. In both cases the mail headers become Camel headers.

true

boolean

bcc (producer)

The Bcc recipients of the mails the producer sends, separated by comma or semicolon. Ignored when useHeaderRecipients=true and the message has a To, Cc or Bcc header.

String

cc (producer)

The Cc recipients of the mails the producer sends, separated by comma or semicolon. Ignored when useHeaderRecipients=true and the message has a To, Cc or Bcc header.

String

from (producer)

The From address of the mails the producer sends. The From header of the message is ignored unless useHeaderFrom=true.

camel@localhost

String

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

replyTo (producer)

The Reply-To addresses of the mails the producer sends, separated by comma or semicolon. The Reply-To header of the message is ignored unless useHeaderReplyTo=true.

String

subject (producer)

The Subject of the message being sent. The Subject message header is ignored unless useHeaderSubject=true, in which case it overrides this option.

String

to (producer)

The To recipients of the mails the producer sends, separated by comma or semicolon. Ignored when useHeaderRecipients=true and the message has a To, Cc or Bcc header.

String

useHeaderFrom (producer)

Whether the From and Sender headers of the message set the From and Sender of the mail, overriding the from option. When false (default), both headers are ignored.

false

boolean

useHeaderRecipients (producer)

Whether the To, Cc and Bcc headers of the message set the recipients of the mail. When true and the message has any of these headers, the mail goes only to the addresses in the headers, and the to, cc and bcc options are ignored. When false (default), these headers are ignored and not copied into the mail.

false

boolean

useHeaderReplyTo (producer)

Whether the Reply-To header of the message sets the Reply-To of the mail, overriding the replyTo option. When false (default), the header is ignored.

false

boolean

useHeaderSubject (producer)

Whether the Subject header of the message sets the subject of the mail, overriding the subject option. When false (default), the header is ignored.

false

boolean

javaMailSender (producer (advanced))

A custom JavaMailSender that the producer sends the mails with. Camel sets the host, port, username, password, authenticator, protocol and Jakarta Mail session on it where it has none. The default DefaultJavaMailSender connects a Transport for each mail it sends. The consumer does not use it.

JavaMailSender

additionalJavaMailProperties (advanced)

Jakarta Mail session properties to add to the ones Camel sets from the other options, replacing them on the same key, for example mail.smtp.starttls.enable=true. In the endpoint URI, each option whose name starts with mail. is such a property. Ignored when javaMailProperties or session is set. This is a multi-value option with prefix: mail.

Properties

alternativeBodyHeader (advanced)

The name of the message header that holds the plain text alternative of the body. When the message has this header, the producer sends a multipart/alternative mail with that text and the body (in contentType, typically text/html) as its two parts, and removes the header.

CamelMailAlternativeBody

String

attachmentsContentTransferEncodingResolver (advanced)

A resolver that sets the Content-Transfer-Encoding (for example base64) of each attachment the producer adds. When it returns null, Jakarta Mail chooses the encoding.

AttachmentsContentTransferEncodingResolver

authenticator (advanced)

A MailAuthenticator (a jakarta.mail.Authenticator) that supplies the user name and password each time Camel connects, instead of the username and password options. Use it for credentials that change, such as OAuth2 access tokens that expire.

MailAuthenticator

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

configuration (advanced)

A MailConfiguration whose options are the defaults of every endpoint of the component (each endpoint uses a copy of it).

MailConfiguration

connectionTimeout (advanced)

The timeout in milliseconds for connecting to the mail server and for reading from the connection: Camel sets it as the connectiontimeout and timeout properties of the protocol in the Jakarta Mail session (for example mail.imaps.connectiontimeout and mail.imaps.timeout). 0 or a negative value means no timeout. Not applied when javaMailProperties or session is set.

30000

int

contentType (advanced)

The Content-Type of the mail body the producer sends, for example text/html for an HTML mail. The contentType or Content-Type header of the message overrides it. When a text type has no charset, the charset of the exchange, else the default charset of Jakarta Mail, is added.

text/plain

String

contentTypeResolver (advanced)

A resolver that sets the Content-Type of each attachment the producer adds, from its file name. When it returns null, the content type of the DataHandler of the attachment is used.

ContentTypeResolver

debugMode (advanced)

Whether to turn on the debug output of Jakarta Mail (Session.setDebug), which prints the protocol commands and responses to System.out. Not applied when a session is set.

false

boolean

ignoreUnsupportedCharset (advanced)

Whether the producer removes a charset that the JVM does not support from the Content-Type (logging a WARN) instead of failing to send the mail. A text body then gets the default charset of Jakarta Mail.

false

boolean

ignoreUriScheme (advanced)

Whether to ignore the scheme of the endpoint URI when configuring the mail protocol. By default the scheme (imap, imaps, pop3, pop3s, smtp or smtps) sets the protocol used to talk to the mail server. Enable this to keep a protocol that was already configured on the mail configuration, for example one shared via the component.

false

boolean

javaMailProperties (advanced)

The Jakarta Mail session properties to use instead of the ones Camel creates: Camel then adds neither the JVM system properties nor the properties it sets from the other options (host, port, auth, connectionTimeout, sslContextParameters), and ignores additionalJavaMailProperties. Not applied when session is set.

Properties

maxMultipartDepth (advanced)

The maximum nesting depth of multipart MIME parts the consumer descends into when extracting attachments. A message nested deeper than this has its deeper parts skipped, so a crafted deeply nested multipart cannot exhaust the stack. Increase it only if a legitimate source produces unusually deep nesting.

20

int

session (advanced)

A jakarta.mail.Session to use instead of the one Camel creates, for example a session managed by an application server. Camel then does not apply javaMailProperties, additionalJavaMailProperties, connectionTimeout, sslContextParameters and debugMode, and the producer takes the host and port from the mail.smtp.host (or mail.smtps.host) and mail.smtp.port (or mail.smtps.port) properties of the session when they are set. The username and password options are still used to connect.

Session

useInlineAttachments (advanced)

Whether the producer adds the attachments of the message with the Content-Disposition inline instead of attachment. With an alternative body (see alternativeBodyHeader), the inline attachments go with the body into a multipart/related part, so an HTML body can refer to them by Content-ID: an attachment whose name starts with cid: gets the rest of the name as Content-ID.

false

boolean

headerFilterStrategy (filter)

A HeaderFilterStrategy for every endpoint of the component, instead of the default MailHeaderFilterStrategy. It decides which headers of the Camel message the producer copies into the mail, and which headers of the mail the consumer maps to Camel headers.

HeaderFilterStrategy

healthCheckConsumerEnabled (health)

Used for enabling or disabling all consumer based health checks from this component.

true

boolean

healthCheckProducerEnabled (health)

Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true.

true

boolean

password (security)

The password to log in to the mail server. Ignored when an authenticator is set.

String

sslContextParameters (security)

The SSL/TLS configuration (key store, trust store, protocols) of the connection to the mail server. Used for imaps, pop3s and smtps, and for imap, pop3 and smtp when STARTTLS is turned on in additionalJavaMailProperties, for example with mail.smtp.starttls.enable=true or mail.smtp.starttls.required=true (mail.imap. or mail.pop3. for the others). Not applied when javaMailProperties or session is set. Without it, the default SSL socket factory of the JVM is used.

SSLContextParameters

useGlobalSslContextParameters (security)

Enable usage of global SSL context parameters.

false

boolean

useJavaMailSessionPropertiesFromHeaders (security)

Whether to allow dynamic JavaMail session properties (message headers whose key starts with mail.smtp. or mail.smtps.) to override the endpoint configuration on a per-message basis. This is disabled by default. Only enable it when these headers originate exclusively from trusted route logic, never from data crossing a trust boundary (for example HTTP query parameters, or JMS/Kafka messages from untrusted producers). When enabled, an attacker able to set these headers could weaken transport security (such as mail.smtp.ssl.trust or mail.smtp.starttls.enable) or redirect the SMTP connection.

false

boolean

username (security)

The user name to log in to the mail server. It is not used for the login when an authenticator is set. For the producer, when no to, cc or bcc recipient is configured yet, it also sets the to option to this user name, adding an at sign and the host when the user name has no at sign.

String

Endpoint Options

The Mail endpoint is configured using URI syntax:

imap:host:port

With the following path and query parameters:

Path Parameters

Name Description Default Type

host (common)

Required The mail server host name.

String

port (common)

The port of the mail server. When not set, the default port of the protocol is used: 25 for smtp, 465 for smtps, 110 for pop3, 995 for pop3s, 143 for imap and 993 for imaps.

int

Query Parameters

Name Description Default Type

closeFolder (consumer)

Whether the consumer closes the folder after each poll. Closing expunges the mails flagged DELETED (by delete or moveTo). With closeFolder=false and disconnect=false the folder stays open between polls, and deleted mails are removed only when the folder is closed, at the latest when the consumer stops. Keep it true for POP3: a POP3 folder that stays open does not see new mails.

true

boolean

copyTo (consumer)

The IMAP folder to copy a mail to once its exchange completed successfully. The folder is created if it does not exist. The CamelMailCopyTo header overrides this option for a mail. Ignored for POP3.

String

decodeFilename (consumer)

Whether the consumer decodes MIME encoded file names of attachments with MimeUtility.decodeText. This is like setting the system property mail.mime.decodefilename=true.

false

boolean

delete (consumer)

Whether the consumer deletes a mail once its exchange completed successfully: it sets the DELETED flag on the mail instead of the SEEN flag, and the mail is removed from the server when the folder is closed (see closeFolder). The CamelMailDelete header overrides this option for a mail. POP3 keeps no SEEN flag on the server, so with POP3 deleting is how a consumed mail is not consumed again.

false

boolean

disconnect (consumer)

Whether the consumer closes the folder and disconnects from the mail server (Store.close) after each poll, so that every poll connects again. By default the connection stays open between polls.

false

boolean

handleFailedMessage (consumer)

Whether the consumer passes the exception of a mail that it cannot retrieve or map to an exchange to its exception handler (which logs it at WARN, or with bridgeErrorHandler=true routes it to the error handler of the route), and goes on with the next mail. When neither this option nor skipFailedMessage is set, the poll fails and none of its mails is routed.

false

boolean

maxMessagesPerPoll (consumer)

The maximum number of mails the consumer consumes per poll, used when fetchSize is -1. 0 or a negative value (default) means no limit.

int

mimeDecodeHeaders (consumer)

Whether the consumer unfolds the mail header values and decodes their MIME encoded words (MimeUtility.decodeText, for example =?UTF-8?B?…​?=) before it maps them to Camel headers.

false

boolean

moveTo (consumer)

The IMAP folder to move a mail to once its exchange completed successfully: the mail is copied to that folder and flagged DELETED in the polled folder, from which it is removed when the folder is closed (see closeFolder). The folder is created if it does not exist. The CamelMailMoveTo header overrides this option for a mail. Ignored for POP3.

String

peek (consumer)

Whether the consumer sets peek on each IMAP mail (IMAPMessage.setPeek) before reading it, so reading the mail does not set the SEEN flag on the server. The consumer then sets SEEN (or DELETED) only once the exchange completed successfully, so a mail whose exchange failed stays unseen and a later poll consumes it again. With peek=false the server sets SEEN when the content is read, which with mapMailMessage=true happens for every mail of a poll when it is retrieved: a mail that fails or is not routed (the consumer stops, or an earlier mail of the poll failed) is then not polled again with unseen=true. IMAP only.

true

boolean

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

skipFailedMessage (consumer)

Whether the consumer skips a mail that it cannot retrieve or map to an exchange (for example a malformed mail), logging it at DEBUG, and goes on with the next mail. When neither this option nor handleFailedMessage is set, the poll fails and none of its mails is routed. Takes precedence over handleFailedMessage.

false

boolean

unseen (consumer)

Whether the consumer polls only the mails that do not have the SEEN flag. Ignored when a searchTerm is set. POP3 keeps no flags on the server, so every mail counts as unseen each time the folder is opened: use delete=true, or an idempotentRepository with idempotentRepositoryRemoveOnCommit=false, to not consume a mail again.

true

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

failOnDuplicateFileAttachment (consumer (advanced))

Whether to fail processing the mail if the mail message contains attachments with duplicate file names. If set to false, then the duplicate attachment is skipped and a WARN is logged. If set to true, then an exception is thrown failing to process the mail message.

false

boolean

fetchSize (consumer (advanced))

The maximum number of mails the consumer consumes per poll, which avoids loading the mail server when a folder holds many mails. -1 (default) sets no limit here, so maxMessagesPerPoll applies. 0 skips every poll, so no mail is consumed. A value of 0 or more takes precedence over maxMessagesPerPoll.

-1

int

folderName (consumer (advanced))

The name of the folder the consumer polls. With POP3, only INBOX exists.

INBOX

String

generateMissingAttachmentNames (consumer (advanced))

How the consumer names an attachment (a part with the Content-Disposition attachment or inline) that has no file name: never (default) leaves it without a name, so it is not extracted as an attachment; uuid names it with a random UUID.

String

handleDuplicateAttachmentNames (consumer (advanced))

How the consumer handles attachments of a mail that have the same file name: never (default) keeps the first one and skips the others, or fails with failOnDuplicateFileAttachment=true; uuidPrefix renames them to uuid_filename.ext; uuidSuffix renames them to filename_uuid.ext.

String

mailUidGenerator (consumer (advanced))

A MailUidGenerator that computes the key of a mail: the key in the idempotentRepository, and with POP3 the key that finds the mail again to mark it once its exchange completed. The default uses the Message-ID header, else a hash of all the mail headers, else the message number.

MailUidGenerator

mapMailMessage (consumer (advanced))

Whether the consumer maps the mail to the Camel message: the content of the mail becomes the body (a String for a text mail, a Multipart for a multipart mail) and the attachments become Camel attachments, all read from the server when the mail is polled. When false, the body is the jakarta.mail.Message itself, no attachments are extracted, and the content is read only when the route reads it. In both cases the mail headers become Camel headers.

true

boolean

pollStrategy (consumer (advanced))

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

PollingConsumerPollStrategy

postProcessAction (consumer (advanced))

A MailBoxPostProcessAction that the consumer calls with the folder after a poll routed its mails, for example to clean up old mails. It is not called when the folder is empty or the poll failed.

MailBoxPostProcessAction

bcc (producer)

The Bcc recipients of the mails the producer sends, separated by comma or semicolon. Ignored when useHeaderRecipients=true and the message has a To, Cc or Bcc header.

String

cc (producer)

The Cc recipients of the mails the producer sends, separated by comma or semicolon. Ignored when useHeaderRecipients=true and the message has a To, Cc or Bcc header.

String

from (producer)

The From address of the mails the producer sends. The From header of the message is ignored unless useHeaderFrom=true.

camel@localhost

String

replyTo (producer)

The Reply-To addresses of the mails the producer sends, separated by comma or semicolon. The Reply-To header of the message is ignored unless useHeaderReplyTo=true.

String

subject (producer)

The Subject of the message being sent. The Subject message header is ignored unless useHeaderSubject=true, in which case it overrides this option.

String

to (producer)

The To recipients of the mails the producer sends, separated by comma or semicolon. Ignored when useHeaderRecipients=true and the message has a To, Cc or Bcc header.

String

useHeaderFrom (producer)

Whether the From and Sender headers of the message set the From and Sender of the mail, overriding the from option. When false (default), both headers are ignored.

false

boolean

useHeaderRecipients (producer)

Whether the To, Cc and Bcc headers of the message set the recipients of the mail. When true and the message has any of these headers, the mail goes only to the addresses in the headers, and the to, cc and bcc options are ignored. When false (default), these headers are ignored and not copied into the mail.

false

boolean

useHeaderReplyTo (producer)

Whether the Reply-To header of the message sets the Reply-To of the mail, overriding the replyTo option. When false (default), the header is ignored.

false

boolean

useHeaderSubject (producer)

Whether the Subject header of the message sets the subject of the mail, overriding the subject option. When false (default), the header is ignored.

false

boolean

javaMailSender (producer (advanced))

A custom JavaMailSender that the producer sends the mails with. Camel sets the host, port, username, password, authenticator, protocol and Jakarta Mail session on it where it has none. The default DefaultJavaMailSender connects a Transport for each mail it sends. The consumer does not use it.

JavaMailSender

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

additionalJavaMailProperties (advanced)

Jakarta Mail session properties to add to the ones Camel sets from the other options, replacing them on the same key, for example mail.smtp.starttls.enable=true. In the endpoint URI, each option whose name starts with mail. is such a property. Ignored when javaMailProperties or session is set. This is a multi-value option with prefix: mail.

Properties

alternativeBodyHeader (advanced)

The name of the message header that holds the plain text alternative of the body. When the message has this header, the producer sends a multipart/alternative mail with that text and the body (in contentType, typically text/html) as its two parts, and removes the header.

CamelMailAlternativeBody

String

attachmentsContentTransferEncodingResolver (advanced)

A resolver that sets the Content-Transfer-Encoding (for example base64) of each attachment the producer adds. When it returns null, Jakarta Mail chooses the encoding.

AttachmentsContentTransferEncodingResolver

authenticator (advanced)

A MailAuthenticator (a jakarta.mail.Authenticator) that supplies the user name and password each time Camel connects, instead of the username and password options. Use it for credentials that change, such as OAuth2 access tokens that expire.

MailAuthenticator

binding (advanced)

A custom MailBinding that converts between the Camel message and the mail. The options that configure the default binding (such as decodeFilename, mapMailMessage, maxMultipartDepth, headerFilterStrategy and contentTypeResolver) are not applied to a custom binding.

MailBinding

connectionTimeout (advanced)

The timeout in milliseconds for connecting to the mail server and for reading from the connection: Camel sets it as the connectiontimeout and timeout properties of the protocol in the Jakarta Mail session (for example mail.imaps.connectiontimeout and mail.imaps.timeout). 0 or a negative value means no timeout. Not applied when javaMailProperties or session is set.

30000

int

contentType (advanced)

The Content-Type of the mail body the producer sends, for example text/html for an HTML mail. The contentType or Content-Type header of the message overrides it. When a text type has no charset, the charset of the exchange, else the default charset of Jakarta Mail, is added.

text/plain

String

contentTypeResolver (advanced)

A resolver that sets the Content-Type of each attachment the producer adds, from its file name. When it returns null, the content type of the DataHandler of the attachment is used.

ContentTypeResolver

debugMode (advanced)

Whether to turn on the debug output of Jakarta Mail (Session.setDebug), which prints the protocol commands and responses to System.out. Not applied when a session is set.

false

boolean

headerFilterStrategy (advanced)

A HeaderFilterStrategy that decides which headers of the Camel message the producer copies into the mail as MIME headers, and which headers of the mail the consumer maps to Camel headers. The default drops the headers starting with Camel, and for the consumer also the headers starting with mail.smtp. or mail.smtps.; the producer copies every other header, apart from the ones the useHeader options control.

HeaderFilterStrategy

ignoreUnsupportedCharset (advanced)

Whether the producer removes a charset that the JVM does not support from the Content-Type (logging a WARN) instead of failing to send the mail. A text body then gets the default charset of Jakarta Mail.

false

boolean

ignoreUriScheme (advanced)

Whether to ignore the scheme of the endpoint URI when configuring the mail protocol. By default the scheme (imap, imaps, pop3, pop3s, smtp or smtps) sets the protocol used to talk to the mail server. Enable this to keep a protocol that was already configured on the mail configuration, for example one shared via the component.

false

boolean

javaMailProperties (advanced)

The Jakarta Mail session properties to use instead of the ones Camel creates: Camel then adds neither the JVM system properties nor the properties it sets from the other options (host, port, auth, connectionTimeout, sslContextParameters), and ignores additionalJavaMailProperties. Not applied when session is set.

Properties

maxMultipartDepth (advanced)

The maximum nesting depth of multipart MIME parts the consumer descends into when extracting attachments. A message nested deeper than this has its deeper parts skipped, so a crafted deeply nested multipart cannot exhaust the stack. Increase it only if a legitimate source produces unusually deep nesting.

20

int

session (advanced)

A jakarta.mail.Session to use instead of the one Camel creates, for example a session managed by an application server. Camel then does not apply javaMailProperties, additionalJavaMailProperties, connectionTimeout, sslContextParameters and debugMode, and the producer takes the host and port from the mail.smtp.host (or mail.smtps.host) and mail.smtp.port (or mail.smtps.port) properties of the session when they are set. The username and password options are still used to connect.

Session

useInlineAttachments (advanced)

Whether the producer adds the attachments of the message with the Content-Disposition inline instead of attachment. With an alternative body (see alternativeBodyHeader), the inline attachments go with the body into a multipart/related part, so an HTML body can refer to them by Content-ID: an attachment whose name starts with cid: gets the rest of the name as Content-ID.

false

boolean

idempotentRepository (filter)

An IdempotentRepository that lets several consumers (in one or more applications) consume the same mailbox: a consumer routes a mail only when it can add the key of the mail (see mailUidGenerator) to the repository. The key is removed again when the exchange fails, so the mail can be consumed again. By default no repository is used.

IdempotentRepository

idempotentRepositoryRemoveOnCommit (filter)

Whether the consumer removes the key of a mail from the idempotentRepository once its exchange completed successfully (default), or keeps it (confirm). Removing it suits mails that are marked SEEN, moved or deleted, as no later poll finds them. Keep the key (false) when a consumed mail can match a later poll, for example with POP3 without delete=true, a custom searchTerm or unseen=false, so it is not consumed again.

true

boolean

searchTerm (filter)

A jakarta.mail.search.SearchTerm that selects the mails to consume, for example by subject, body, from or sent date. It replaces the unseen option, so include the unseen condition if needed. In the endpoint URI it can also be built with the searchTerm. options (searchTerm.subject, searchTerm.from, searchTerm.fromSentDate=now-24h and so on), which match only unseen mails unless searchTerm.unseen=false. IMAP runs the search on the server where it can; with POP3, Jakarta Mail runs it in the client. This is a multi-value option with prefix: searchTerm.

SearchTerm

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

int

delay (scheduler)

Milliseconds before the next poll.

60000

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

healthCheckMaxPollDuration (scheduler)

How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off.

0

long

initialDelay (scheduler)

Milliseconds before the first poll starts.

1000

long

repeatCount (scheduler)

Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.

0

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

ScheduledExecutorService

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler.

none

Object

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler.

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

password (security)

The password to log in to the mail server. Ignored when an authenticator is set.

String

sslContextParameters (security)

The SSL/TLS configuration (key store, trust store, protocols) of the connection to the mail server. Used for imaps, pop3s and smtps, and for imap, pop3 and smtp when STARTTLS is turned on in additionalJavaMailProperties, for example with mail.smtp.starttls.enable=true or mail.smtp.starttls.required=true (mail.imap. or mail.pop3. for the others). Not applied when javaMailProperties or session is set. Without it, the default SSL socket factory of the JVM is used.

SSLContextParameters

useJavaMailSessionPropertiesFromHeaders (security)

Whether to allow dynamic JavaMail session properties (message headers whose key starts with mail.smtp. or mail.smtps.) to override the endpoint configuration on a per-message basis. This is disabled by default. Only enable it when these headers originate exclusively from trusted route logic, never from data crossing a trust boundary (for example HTTP query parameters, or JMS/Kafka messages from untrusted producers). When enabled, an attacker able to set these headers could weaken transport security (such as mail.smtp.ssl.trust or mail.smtp.starttls.enable) or redirect the SMTP connection.

false

boolean

username (security)

The user name to log in to the mail server. It is not used for the login when an authenticator is set. For the producer, when no to, cc or bcc recipient is configured yet, it also sets the to option to this user name, adding an at sign and the host when the user name has no at sign.

String

sortTerm (sort)

The order in which the consumer routes the mails of a poll: a comma-separated list of arrival, cc, date, from, size, subject and to, where reverse before a term sorts by it in descending order (for example reverse,date), or a SortTerm[] bean. An IMAP server with the SORT capability sorts the mails; otherwise (POP3, or no SORT) Camel sorts them itself. Sorting comes before the fetchSize or maxMessagesPerPoll limit, so it also selects the mails a limited poll consumes.

SortTerm[]

Message Headers

The Mail component supports the following message header(s), which is/are listed below:

Name Description Default Type

Subject (common)

Constant: MAIL_SUBJECT

The Subject of the mail. The consumer sets it from the mail. The producer uses it only with useHeaderSubject=true.

String

From (common)

Constant: MAIL_FROM

The From address of the mail. The consumer sets it from the mail. The producer uses it, and the Sender header, only with useHeaderFrom=true.

String

Sender (producer)

Constant: MAIL_SENDER

The Sender address of the mail to send, which the producer sets on the mail only with useHeaderFrom=true.

String

To (common)

Constant: MAIL_TO

The To recipients of the mail, separated by comma or semicolon. The consumer sets it from the mail. The producer uses it, with the Cc and Bcc headers, only with useHeaderRecipients=true.

String

Cc (common)

Constant: MAIL_CC

The Cc recipients of the mail, separated by comma or semicolon. The consumer sets it from the mail. The producer uses it only with useHeaderRecipients=true.

String

Bcc (common)

Constant: MAIL_BCC

The Bcc recipients of the mail to send, separated by comma or semicolon. The producer uses it only with useHeaderRecipients=true.

String

Reply-To (common)

Constant: MAIL_REPLY_TO

The Reply-To addresses of the mail, separated by comma or semicolon. The consumer sets it from the mail. The producer uses it only with useHeaderReplyTo=true.

String

contentType (common)

Constant: MAIL_CONTENT_TYPE

The Content-Type of the mail body the producer sends, overriding the contentType option. Without this header, the producer uses the Content-Type header when it is set.

String

CamelMessageTimestamp (consumer)

Constant: MESSAGE_TIMESTAMP

The sent date of the mail, in milliseconds since the epoch. Only set when the mail has a sent date.

long

mail.smtp. (producer)

Constant: MAIL_SMTP_PROPERTIES_PREFIX

The prefix of the headers that carry Jakarta Mail session properties for this mail, such as mail.smtp.from. The producer uses them, with this prefix, for a new mail sender only with useJavaMailSessionPropertiesFromHeaders=true, and not with a custom JavaMailSender.

Object

mail.smtps. (producer)

Constant: MAIL_SMTPS_PROPERTIES_PREFIX

The prefix of the headers that carry Jakarta Mail session properties for this mail, such as mail.smtps.from. Used as mail.smtp. is, when the message has no header with the mail.smtp. prefix.

Object

CamelMailCopyTo (consumer)

Constant: MAIL_COPY_TO

The IMAP folder to copy this mail to once its exchange completed successfully, overriding the copyTo option.

String

CamelMailMoveTo (consumer)

Constant: MAIL_MOVE_TO

The IMAP folder to move this mail to once its exchange completed successfully, overriding the moveTo option.

String

CamelMailDelete (consumer)

Constant: MAIL_DELETE

Whether to delete this mail once its exchange completed successfully, overriding the delete option.

boolean

CamelMailAlternativeBody (producer)

Constant: MAIL_ALTERNATIVE_BODY

The alternative body of the mail, as plain text. When set, the mail is sent as multipart/alternative with this text and the body (typically HTML) as its two parts, so mail clients that cannot show HTML show the text. The alternativeBodyHeader option can change the name of this header.

String

CamelMailMessageId (common)

Constant: MAIL_MESSAGE_ID

The Message-ID of the mail the producer sent.

String

CamelSplitAttachmentId (consumer)

Constant: MAIL_SPLIT_ATTACHMENT_ID

The name of the attachment, on each message produced by SplitAttachmentsExpression.

String

Message Body

The message body at each side of the Mail component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

text, stream or pojo

The content of the mail an imap or pop3 consumer reads: a String for text/plain, text/html and text/xml, a stream for another content type, and a jakarta.mail Multipart for a multipart mail, which converts to the text of its first text part, with the files in the attachments. The jakarta.mail.Message itself with mapMailMessage=false.

  • With mapMailMessage=false: pojo (jakarta.mail.Message)

Not known when binding is set.

Producer input

null, text, bytes, stream or file

The text of the mail smtp sends, in the contentType: bytes, a stream or a file are read as text, so send binary content as an attachment, and no body sends an empty text. A jakarta.mail MimeMessage is sent as it is, and a Map or a POJO as its toString(): marshal it first.

Not known when binding is set.

Producer output

unchanged

Unchanged, with the Message-ID of the mail in the CamelMailMessageId header.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

Typically, you specify a URI with login credentials as follows:

SMTP endpoint example
smtp://[username@]host[:port][?password=somepwd]

Alternatively, it is possible to specify both the username and the password as query options:

smtp://host[:port]?password=somepwd&username=someuser

For example:

smtp://mycompany.mailserver:30?password=tiger&username=scott

Component alias names

  • IMAP

  • IMAPs

  • POP3s

  • POP3s

  • SMTP

  • SMTPs

Default ports

Default port numbers are supported. If the port number is omitted, Camel determines the port number to use based on the protocol.

Protocol Default Port Number

SMTP

25

SMTPS

465

POP3

110

POP3S

995

IMAP

143

IMAPS

993

SSL support

The underlying mail framework is responsible for providing SSL support. You may either configure SSL/TLS support by completely specifying the necessary Java Mail API configuration options, or you may provide a configured SSLContextParameters through the component or endpoint configuration.

Using the JSSE Configuration Utility

The mail component supports SSL/TLS configuration through the Camel JSSE Configuration Utility. This utility greatly decreases the amount of component-specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the mail component.

Programmatic configuration of the endpoint

Java-only: programmatic SSLContextParameters configuration and registry binding
KeyStoreParameters ksp = new KeyStoreParameters();
ksp.setResource("/users/home/server/truststore.jks");
ksp.setPassword("keystorePassword");
TrustManagersParameters tmp = new TrustManagersParameters();
tmp.setKeyStore(ksp);
SSLContextParameters scp = new SSLContextParameters();
scp.setTrustManagers(tmp);
Registry registry = ...
registry.bind("sslContextParameters", scp);
...
from(...)
    .to("smtps://smtp.google.com?username=user@gmail.com&password=password&sslContextParameters=#sslContextParameters");

Spring DSL based configuration of endpoint

...
<camel:sslContextParameters id="sslContextParameters">
  <camel:trustManagers>
    <camel:keyStore resource="/users/home/server/truststore.jks" password="keystorePassword"/>
  </camel:trustManagers>
</camel:sslContextParameters>...
...
<to uri="smtps://smtp.google.com?username=user@gmail.com&amp;password=password&amp;sslContextParameters=#sslContextParameters"/>...

Configuring JavaMail Directly

Camel uses Jakarta JavaMail, which only trusts certificates issued by well-known Certificate Authorities (the default JVM trust configuration). If you issue your own certificates, you have to import the CA certificates into the JVM’s Java trust/key store files, override the default JVM trust/key store files (see SSLNOTES.txt in JavaMail for details).

Mail Message Content

Camel uses the message exchange’s IN body as the MimeMessage text content. The body is converted to String.class: bytes, a stream or a file are read as text, so send binary content as an attachment, and a Map or a POJO is sent as its toString(). A body that is a jakarta.mail.internet.MimeMessage is sent as it is, with its own recipients and subject.

Mails are sent with smtp or smtps. A producer on imap, imaps, pop3 or pop3s fails when it is created.

The text is encoded in the charset of the contentType option (or of the Content-Type header), else in the charset of the exchange (the CamelCharsetName exchange property). When neither has a charset, the text is encoded in the default charset of Jakarta Mail (the mail.mime.charset system property, else the JVM default charset, which is UTF-8 unless changed), and that charset is added to the Content-Type of the mail.

When the body is a jakarta.mail.internet.MimeMessage, it is sent as it is. A message read from a mail store, such as the body of a mail consumer with mapMailMessage=false, is read-only, so a copy of it is sent.

When a mail consumer gives a multipart mail, the body converts to the text of its first text part (a text part without a content handler in Jakarta Mail, such as text/csv, is read in the charset of the part), or to null when the mail has no text part.

Camel copies all of the exchange’s IN headers to the MimeMessage headers.

The subject of the MimeMessage can be configured using a header property on the IN message. The Subject header is only used when the useHeaderSubject=true option is enabled on the endpoint (default false); otherwise the header is ignored and the subject endpoint option is used. The code below demonstrates this:

  • Java

  • XML

  • YAML

from("direct:a").setHeader("subject", constant(subject)).to("smtp://james2@localhost?useHeaderSubject=true");
<route>
  <from uri="direct:a"/>
  <setHeader name="subject">
    <constant>some subject</constant>
  </setHeader>
  <to uri="smtp://james2@localhost?useHeaderSubject=true"/>
</route>
- route:
    from:
      uri: direct:a
      steps:
        - setHeader:
            name: subject
            expression:
              constant:
                expression: "some subject"
        - to:
            uri: smtp://james2@localhost
            parameters:
              useHeaderSubject: true

The same applies for other MimeMessage headers such as recipients, so you can use a header property as To. The To/CC/BCC, From and Subject headers are only honoured when useHeaderRecipients=true, useHeaderFrom=true and useHeaderSubject=true respectively are enabled on the endpoint (all default to false, see the useHeader* options table below):

Java-only: ProducerTemplate API with mail headers
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("To", "davsclaus@apache.org");
headers.put("From", "jstrachan@apache.org");
headers.put("Subject", "Camel rocks");
headers.put("CamelFileName", "fileOne");
headers.put("org.apache.camel.test", "value");

String body = "Hello Claus.\nYes it does.\n\nRegards James.";
template.sendBodyAndHeaders("smtp://davsclaus@apache.org?useHeaderRecipients=true&useHeaderFrom=true&useHeaderSubject=true",
        body, headers);

When using the MailProducer to send the mail to server, you should be able to get the message id of the MimeMessage with the key CamelMailMessageId from the Camel message header.

Recipient headers and pre-configured recipients

By default (useHeaderRecipients=false, the default since Camel 4.21) the To, CC and BCC message headers are ignored and the mail is sent to the recipients pre-configured in the endpoint URI.

When useHeaderRecipients=true is set, the recipients specified in the message headers take precedence over recipients pre-configured in the endpoint URI. The idea is that if you provide any recipients in the message headers, that is what you get. The recipients pre-configured in the endpoint URI are treated as a fallback.

In the sample code below, the endpoint enables useHeaderRecipients=true, so the email message is sent to davsclaus@apache.org, because it takes precedence over the pre-configured recipient, info@mycompany.com. Without useHeaderRecipients=true the to header would be ignored and the mail sent to info@mycompany.com. Any CC and BCC settings in the endpoint URI are also ignored, and those recipients will not receive any mail. The choice between headers and pre-configured settings is all or nothing: the mail component either takes the recipients exclusively from the headers or exclusively from the pre-configured settings. It is not possible to mix and match headers and pre-configured settings.

Java-only: ProducerTemplate API showing header override of pre-configured recipient
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("to", "davsclaus@apache.org");

template.sendBodyAndHeaders("smtp://admin@localhost?to=info@mycompany.com&useHeaderRecipients=true", "Hello World", headers);

Letting message headers override the endpoint configuration

By default the recipients, sender, subject and reply-to address configured on the endpoint cannot be overridden by message headers. Four opt-in @UriParam options let a route allow message headers to override them:

Option Default Effect when set to true

useHeaderRecipients

false

Message To/CC/BCC headers can override the endpoint URI recipients.

useHeaderFrom

false

Message From/Sender headers can override the endpoint URI sender.

useHeaderSubject

false

Message Subject header can override the endpoint URI subject.

useHeaderReplyTo

false

Message Reply-To header can override the endpoint URI replyTo.

All four default to false since Camel 4.21. Set an option to true to let the matching message headers override the endpoint configuration.

Only enable the options a route needs, and only when the headers come from a trusted source. For routes where message headers originate from an untrusted source (for example messages bridged from an HTTP endpoint, a JMS queue, or a Kafka topic), allowing inbound headers to override recipients, sender, subject, or reply-to addresses can enable an attacker to redirect mail, intercept replies, forge the sender address, or inject arbitrary subjects. If such headers may reach the mail endpoint, leave the options disabled or remove the headers before sending.

In the example below the route computes the recipients and the subject itself, so it enables useHeaderRecipients and useHeaderSubject, while the sender and reply-to address stay fixed to the endpoint configuration:

  • Java

  • XML

  • YAML

.to("smtp://relay@mailhost?to=safe@mycompany.com&from=noreply@mycompany.com&useHeaderRecipients=true&useHeaderSubject=true");
<to uri="smtp://relay@mailhost?to=safe@mycompany.com&amp;from=noreply@mycompany.com&amp;useHeaderRecipients=true&amp;useHeaderSubject=true"/>
- route:
    from:
      uri: direct:send
      steps:
        - to:
            uri: smtp://relay@mailhost
            parameters:
              to: "safe@mycompany.com"
              from: "noreply@mycompany.com"
              useHeaderRecipients: true
              useHeaderSubject: true
These options do not strip the headers from the exchange. See the Deployment hardening section of the Security Model.

Multiple recipients for easier configuration

It is possible to set multiple recipients using a comma-separated or a semicolon-separated list. This applies both to header settings and to settings in an endpoint URI. For example:

Java-only: programmatic header map with semicolon-separated recipients
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("to", "davsclaus@apache.org ; jstrachan@apache.org ; ningjiang@apache.org");

The preceding example uses a semicolon, ;, as the separator character.

Setting sender name and email

You can specify recipients in the format, name <email>, to include both the name and the email address of the recipient.

For example, you define the following headers on the message:

Java-only: programmatic header map construction
Map headers = new HashMap();
map.put("Subject", "Camel is cool");
map.put("From", "James Strachan <jstrachan@apache.org>");
map.put("To", "Claus Ibsen <davsclaus@apache.org>");
map.put("Cc", "An Other <another@example.com>");
map.put("Bcc", "An Other <another@example.com>");
map.put("Reply-To", "An Other <another@example.com>");

JavaMail API (ex SUN JavaMail)

JavaMail API is used under the hood for consuming and producing mails. We encourage end-users to consult these references when using either POP3 or IMAP protocol. Note particularly that POP3 has a much more limited set of features than IMAP.

Polling Optimization

The parameter maxMessagePerPoll and fetchSize allow you to restrict the number of messages that should be processed for each poll. These parameters should help to prevent bad performance when working with folders that contain a lot of messages. In previous versions, these parameters have been evaluated too late, so that big mailboxes could still cause performance problems. With Camel 3.1, these parameters are evaluated earlier during the poll to avoid these problems.

Consuming one mailbox with several consumers

Several consumers (in one or more applications) can consume the same mailbox when they share an idempotentRepository: a consumer routes a mail only when it could add the key of the mail to the repository. Once the mail is routed, it is marked as SEEN (or deleted), and by default its key is removed from the repository (idempotentRepositoryRemoveOnCommit=true). Another consumer may have found the mail in its search before that, and add the key after it was removed. With IMAP, the default unseen=true and no custom searchTerm, and with peek=true, that consumer asks the server whether the mail is SEEN now (one request for each mail whose key it added), and does not route it again. Otherwise (POP3, which has no SEEN flag, a custom searchTerm, unseen=false or peek=false), set idempotentRepositoryRemoveOnCommit=false so the key of a consumed mail stays in the repository, and use a repository that keeps the keys long enough.

Examples

We start with a simple route that sends the messages received from a JMS queue as emails. The email account is the admin account on mymailserver.com.

  • Java

  • XML

  • YAML

from("jms://queue:subscription").to("smtp://admin@mymailserver.com?password=secret");
<route>
  <from uri="jms://queue:subscription"/>
  <to uri="smtp://admin@mymailserver.com?password=secret"/>
</route>
- route:
    from:
      uri: jms://queue:subscription
      steps:
        - to:
            uri: smtp://admin@mymailserver.com
            parameters:
              password: secret

In the next sample, we poll a mailbox for new emails once every minute.

  • Java

  • XML

  • YAML

from("imap://admin@mymailserver.com?password=secret&unseen=true&delay=60000")
    .to("seda://mails");
<route>
  <from uri="imap://admin@mymailserver.com?password=secret&amp;unseen=true&amp;delay=60000"/>
  <to uri="seda://mails"/>
</route>
- route:
    from:
      uri: imap://admin@mymailserver.com
      parameters:
        password: secret
        unseen: true
        delay: 60000
      steps:
        - to:
            uri: seda://mails

Sending mail with attachment

Attachments are not supported by all Camel components

The Attachments API is based on the Java Activation Framework and is generally only used by the Mail API. Since many of the other Camel components do not support attachments, the attachments could potentially be lost as they propagate along the route. The rule of thumb, therefore, is to add attachments just before sending a message to the mail endpoint.

The mail component supports attachments. In the sample below, we send a mail message containing a plain text message with a logo file attachment.

Java-only: programmatic Exchange and attachment manipulation via Camel API
// create an exchange with a normal body and attachment to be produced as email
Endpoint endpoint = context.getEndpoint("smtp://james@mymailserver.com?password=secret");

// create the exchange with the mail message that is multipart with a file and a Hello World text/plain message.
Exchange exchange = endpoint.createExchange();
AttachmentMessage in = exchange.getIn(AttachmentMessage.class);
in.setBody("Hello World");
DefaultAttachment att = new DefaultAttachment(new FileDataSource("src/test/data/logo.jpeg"));
att.addHeader("Content-Description", "some sample content");
in.addAttachmentObject("logo.jpeg", att);

// create a producer that can produce the exchange (= send the mail)
Producer producer = endpoint.createProducer();
// start the producer
producer.start();
// and let it go (processes the exchange by sending the email)
producer.process(exchange);

SSL example

In this sample, we want to poll our Google Mail inbox for mails. To download mail onto a local mail client, Google Mail requires you to enable and configure SSL. This is done by logging into your Google Mail account and changing your settings to allow IMAP access. Google has extensive documentation on how to do this.

  • Java

  • XML

  • YAML

from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD&delete=false&unseen=true&delay=60000")
    .to("log:newmail");
<route>
  <from uri="imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&amp;password=YOUR_PASSWORD&amp;delete=false&amp;unseen=true&amp;delay=60000"/>
  <to uri="log:newmail"/>
</route>
- route:
    from:
      uri: imaps://imap.gmail.com
      parameters:
        username: "YOUR_USERNAME@gmail.com"
        password: YOUR_PASSWORD
        delete: false
        unseen: true
        delay: 60000
      steps:
        - to:
            uri: log:newmail

The preceding route polls the Google Mail inbox for new mails once every minute and logs the received messages to the newmail logger category. Running the sample with DEBUG logging enabled, we can monitor the progress in the logs:

2008-05-08 06:32:09,640 DEBUG MailConsumer - Connecting to MailStore imaps//imap.gmail.com:993 (SSL enabled), folder=INBOX
2008-05-08 06:32:11,203 DEBUG MailConsumer - Polling mailfolder: imaps//imap.gmail.com:993 (SSL enabled), folder=INBOX
2008-05-08 06:32:11,640 DEBUG MailConsumer - Fetching 1 messages. Total 1 messages.
2008-05-08 06:32:12,171 DEBUG MailConsumer - Processing message: messageNumber=[332], from=[James Bond <007@mi5.co.uk>], to=YOUR_USERNAME@gmail.com], subject=[...
2008-05-08 06:32:12,187 INFO  newmail - Exchange[MailMessage: messageNumber=[332], from=[James Bond <007@mi5.co.uk>], to=YOUR_USERNAME@gmail.com], subject=[...

Consuming mails with attachment

In this sample, we poll a mailbox and store all attachments from the mails as files. First, we define a route to poll the mailbox. As this sample is based on Google Mail, it uses the same route as shown in the SSL sample:

Java-only: uses custom Processor to handle mail attachments
from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD&delete=false&unseen=true&delay=60000")
    .process(new MyMailProcessor());

Instead of logging the mail, we use a processor where we can process the mail from java code:

Java-only: custom Processor for extracting and saving attachments
public void process(Exchange exchange) throws Exception {
    // the API is a bit clunky, so we need to loop
    AttachmentMessage attachmentMessage = exchange.getMessage(AttachmentMessage.class);
    Map<String, DataHandler> attachments = attachmentMessage.getAttachments();
    if (attachments.size() > 0) {
        for (String name : attachments.keySet()) {
            DataHandler dh = attachments.get(name);
            // get the file name
            String filename = dh.getName();

            // get the content and convert it to byte[]
            byte[] data = exchange.getContext().getTypeConverter()
                              .convertTo(byte[].class, dh.getInputStream());

            // write the data to a file
            FileOutputStream out = new FileOutputStream(filename);
            out.write(data);
            out.flush();
            out.close();
        }
    }
}

As you can see the API to handle attachments is a bit clunky, but it’s there, so you can get the javax.activation.DataHandler so you can handle the attachments using standard API.

How to split a mail message with attachments

In this example, we consume mail messages which may have a number of attachments. What we want to do is to use the Splitter EIP per individual attachment, to process the attachments separately. For example, if the mail message has five attachments, we want the Splitter to process five messages, each having a single attachment. To do this, we need to provide a custom Expression to the Splitter where we provide a List<Message> that contains the five messages with the single attachment.

The code is provided out of the box in Camel 2.10 onwards in the camel-mail component. The code is in the class: org.apache.camel.component.mail.SplitAttachmentsExpression, which you can find the source code here

In the Camel route, you then need to use this Expression in the route as shown below:

If you use XML DSL, then you need to declare a method call expression in the Splitter as shown below

XML-only: method expression with beanType attribute is XML DSL specific
<split>
  <method beanType="org.apache.camel.component.mail.SplitAttachmentsExpression"/>
  <to uri="mock:split"/>
</split>

Each split message has the content of one attachment as its body: a byte array, or a String for a text attachment, with the name of the attachment in the CamelSplitAttachmentId header.

Using custom SearchTerm

You can configure a searchTerm on the MailEndpoint which allows you to filter out unwanted mails.

For example, to filter mails to contain Camel in either Subject or Text, you can do as follows:

  • Java

  • XML

  • YAML

from("imaps://mymailseerver?username=foo&password=secret&searchTerm.subjectOrBody=Camel")
    .to("bean:myBean");
<route>
  <from uri="imaps://mymailseerver?username=foo&amp;password=secret&amp;searchTerm.subjectOrBody=Camel"/>
  <to uri="bean:myBean"/>
</route>
- route:
    from:
      uri: imaps://mymailseerver
      parameters:
        username: foo
        password: secret
        searchTerm.subjectOrBody: Camel
      steps:
        - to:
            uri: bean:myBean

Notice we use the "searchTerm.subjectOrBody" as a parameter key to indicate that we want to search on mail subject or body, to contain the word "Camel".
The class org.apache.camel.component.mail.SimpleSearchTerm has a number of options you can configure:

Or to get the new unseen emails going 24 hours back in time, you can do. Notice the "now-24h" syntax. The fromSentDate, toSentDate, fromReceivedDate and toReceivedDate options take either now, with an optional offset such as -24h, or a fixed date in the yyyy-MM-dd HH:mm:ss format, such as 2026-11-18 14:30:45.

  • Java

  • XML

  • YAML

from("imaps://mymailseerver?username=foo&password=secret&searchTerm.fromSentDate=now-24h")
    .to("bean:myBean");
<route>
  <from uri="imaps://mymailseerver?username=foo&amp;password=secret&amp;searchTerm.fromSentDate=now-24h"/>
  <to uri="bean:myBean"/>
</route>
- route:
    from:
      uri: imaps://mymailseerver
      parameters:
        username: foo
        password: secret
        searchTerm.fromSentDate: now-24h
      steps:
        - to:
            uri: bean:myBean

You can have multiple searchTerm in the endpoint uri configuration. They would then be combined using the AND operator, e.g., so both conditions must match. For example, to get the last unseen emails going back 24 hours which has Camel in the mail subject you can do:

  • Java

  • XML

  • YAML

from("imaps://mymailseerver?username=foo&password=secret&searchTerm.subject=Camel&searchTerm.fromSentDate=now-24h")
    .to("bean:myBean");
<route>
  <from uri="imaps://mymailseerver?username=foo&amp;password=secret&amp;searchTerm.subject=Camel&amp;searchTerm.fromSentDate=now-24h"/>
  <to uri="bean:myBean"/>
</route>
- route:
    from:
      uri: imaps://mymailseerver
      parameters:
        username: foo
        password: secret
        searchTerm.subject: Camel
        searchTerm.fromSentDate: now-24h
      steps:
        - to:
            uri: bean:myBean

The SimpleSearchTerm is designed to be easily configurable from a POJO, so you can also configure it using a <bean> style in XML

XML-only: Spring <bean> configuration for `SimpleSearchTerm`
<bean id="mySearchTerm" class="org.apache.camel.component.mail.SimpleSearchTerm">
  <property name="subject" value="Order"/>
  <property name="to" value="acme-order@acme.com"/>
  <property name="fromSentDate" value="now"/>
 </bean>

You can then refer to this bean, using #beanId in your Camel route as shown:

  • Java

  • XML

  • YAML

from("imaps://mymailseerver?username=foo&password=secret&searchTerm=#mySearchTerm")
    .to("bean:myBean");
<route>
  <from uri="imaps://mymailseerver?username=foo&amp;password=secret&amp;searchTerm=#mySearchTerm"/>
  <to uri="bean:myBean"/>
</route>
- route:
    from:
      uri: imaps://mymailseerver
      parameters:
        username: foo
        password: secret
        searchTerm: "#mySearchTerm"
      steps:
        - to:
            uri: bean:myBean

In Java there is a builder class to build compound SearchTerms using the org.apache.camel.component.mail.SearchTermBuilder class. This allows you to build complex terms such as:

Java-only: programmatic SearchTermBuilder for complex mail filters
// we just want the unseen mails that are not spam
SearchTermBuilder builder = new SearchTermBuilder();

builder.unseen().body(Op.not, "Spam").subject(Op.not, "Spam")
  // which was sent from either foo or bar
  .from("foo@somewhere.com").from(Op.or, "bar@somewhere.com");
  // ... and we could continue building the terms

SearchTerm term = builder.build();

Using headers with additional Java Mail Sender properties

When sending mails, then you can provide dynamic java mail properties for the JavaMailSender from the Exchange as message headers with keys starting with mail.smtp. (or mail.smtps.).

You can set any of the mail.smtp properties which you can find in the Java Mail documentation.

For example, to provide a dynamic uuid in mail.smtp.from (SMTP MAIL command):

Java-only: .method() expression for dynamic UUID generation is Java DSL specific
.setHeader("from", constant("reply2me@foo.com"))
.setHeader("mail.smtp.from", method(UUID.class, "randomUUID"))
.to("smtp://mymailserver:1234?useJavaMailSessionPropertiesFromHeaders=true");
This is only supported when not using a custom JavaMailSender.
This feature is disabled by default and must be explicitly enabled with useJavaMailSessionPropertiesFromHeaders=true. The mail.smtp.* / mail.smtps.* keys are a Camel-internal namespace that is not filtered by any HeaderFilterStrategy, so if these headers can originate from data crossing a trust boundary (for example HTTP query parameters, or JMS/Kafka messages from untrusted producers) an attacker could weaken transport security (such as mail.smtp.ssl.trust or mail.smtp.starttls.enable) or redirect the SMTP connection. Only enable the option when these headers are set exclusively by trusted route logic, and strip the namespace with removeHeaders("mail.smtp.*", "mail.smtps.*") before the producer when bridging an untrusted source. See the Camel Security Model for the general pattern.