Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Removed the default encoding option

...

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

Code Block
xml
xml

<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>

...

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

Code Block

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:

Code Block

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

...

Typically, you specify a URI with login credentials as follows (taking SMTP as an example):

Code Block

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

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

Code Block

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

For example:

Code Block

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

...

Wiki Markup
{div:class=confluenceTableSmall}
|| Property || Default || Description ||
| {{host}} | | The host name or IP address to connect to. |
| {{port}} | See [#DefaultPorts] | The TCP port number to connect on. |
| {{username}} | | The user name on the email server. |
| {{password}} | {{null}} | The password on the email server. |
| {{ignoreUriScheme}} | {{false}} | If {{false}}, Camel uses the scheme to determine the transport protocol (POP, IMAP, SMTP etc.) |
| {{defaultEncoding}} | {{null}} | The default encoding to use for Mime Messages. |
| {{contentType}} | {{text/plain}} | The mail message content type. Use {{text/html}} for HTML mails. |
| {{folderName}} | {{INBOX}} | The folder to poll. |
| {{destination}} | {{username@host}} | *@deprecated* Use the {{to}} option instead. The {{TO}} recipients (receivers of the email). |
| {{to}} | {{username@host}} | The TO recipients (the receivers of the mail). Separate multiple email addresses with a comma. |
| {{replyTo}} | {{alias@host}} | As of *Camel 2.8.4, 2.9.1\+*, the Reply-To recipients (the receivers of the response mail). Separate multiple email addresses with a comma. |
| {{CC}} | {{null}} |The CC recipients (the receivers of the mail). Separate multiple email addresses with a comma. |
| {{BCC}} | {{null}} | The BCC recipients (the receivers of the mail). Separate multiple email addresses with a comma. |
| {{from}} | {{camel@localhost}} | The FROM email address. |
| {{subject}} | | As of *Camel 2.3*, the Subject of the message being sent. Note: Setting the subject in the header takes precedence over this option. |
| {{peek}} | {{true}} | *Camel 2.11.3/2.12.2:* Consumer only. Will mark the {{javax.mail.Message}} as peeked before processing the mail message. This applies to {{IMAPMessage}} messages types only. By using peek the mail will not be eager marked as {{SEEN}} on the mail server, which allows us to rollback the mail message if there is an error processing in Camel. |
| {{delete}} | {{false}} | Deletes the messages after they have been processed. This is done by setting the {{DELETED}} flag on the mail message. If {{false}}, the {{SEEN}} flag is set instead. As of *Camel 2.10* you can override this configuration option by setting a header with the key {{delete}} to determine if the mail should be deleted or not. |
| {{unseen}} | {{true}} | It is possible to configure a consumer endpoint so that it processes only unseen messages (that is, new messages) or all messages. Note that Camel always skips deleted messages. The default option of {{true}} will filter to only unseen messages.  POP3 does not support the {{SEEN}} flag, so this option is not supported in POP3; use IMAP instead. *Important:* This option is *not* in use if you also use {{searchTerm}} options. Instead if you want to disable unseen when using {{searchTerm}}'s then add {{searchTerm.unseen=false}} as a term. |
| {{copyTo}} | {{null}} | *Camel 2.10:* Consumer only. After processing a mail message, it can be copied to a mail folder with the given name. You can override this configuration value, with a header with the key {{copyTo}}, allowing you to copy messages to folder names configured at runtime. | 
| {{fetchSize}} | {{\-1}} | Sets the maximum number of messages to consume during a poll. This can be used to avoid overloading a mail server, if a mailbox folder contains a lot of messages. Default value of {{\-1}} means no fetch size and all messages will be consumed. Setting the value to 0 is a special corner case, where Camel will not consume any messages at all. |
| {{alternativeBodyHeader}} | {{CamelMailAlternativeBody}} | Specifies the key to an IN message header that contains an alternative email body. For example, if you send emails in {{text/html}} format and want to provide an alternative mail body for non-HTML email clients, set the alternative mail body with this key as a header. |
| {{debugMode}} | {{false}} | Enable debug mode on the underlying mail framework. The SUN Mail framework logs the debug messages to {{System.out}} by default. |
| {{connectionTimeout}} | {{30000}} | The connection timeout in milliseconds. Default is 30 seconds. |
| {{consumer.initialDelay}} | {{1000}} | Milliseconds before the polling starts. |
| {{consumer.delay}} | {{60000}} | Camel will poll the mailbox only once a minute by default to avoid overloading the mail server. |
| {{consumer.useFixedDelay}} | {{false}} | Set to {{true}} to use a fixed delay between polls, otherwise fixed rate is used. See [ScheduledExecutorService|http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html] in JDK for details. |
| {{disconnect}} | {{false}} | *Camel 2.8.3/2.9:* Whether the consumer should disconnect after polling. If enabled this forces Camel to connect on each poll. |
| {{closeFolder}} | {{true}} | *Camel 2.10.4:* Whether the consumer should close the folder after polling. Setting this option to {{false}} and having {{disconnect=false}} as well, then the consumer keep the folder open between polls. |
| {{mail.XXX}} | {{null}} | Set any [additional java mail properties|http://java.sun.com/products/javamail/javadocs/index.html]. For instance if you want to set a special property when using POP3 you can now provide the option directly in the URI such as: {{mail.pop3.forgettopheaders=true}}. You can set multiple such options, for example: {{mail.pop3.forgettopheaders=true&mail.mime.encodefilename=true}}. |
| {{mapMailMessage}} | {{true}} | *Camel 2.8:* Specifies whether Camel should map the received mail message to Camel body/headers. If set to true, the body of the mail message is mapped to the body of the Camel IN message and the mail headers are mapped to IN headers. If this option is set to false then the IN message contains a raw {{javax.mail.Message}}. You can retrieve this raw message by calling {{exchange.getIn().getBody(javax.mail.Message.class)}}. |
| {{maxMessagesPerPoll}} | {{0}} | Specifies the maximum number of messages to gather per poll. By default, no maximum is set. Can be used to set a limit of e.g. 1000 to avoid downloading thousands of files when the server starts up. Set a value of 0 or negative to disable this option. |
| {{javaMailSender}} | {{null}} | Specifies a pluggable {{org.springframework.mail.javamail.JavaMailSender}} instance in order to use a custom email implementation. If none provided, Camel uses the default {{org.springframework.mail.javamail.JavaMailSenderImpl}}. |
| {{ignoreUnsupportedCharset}} | {{false}} | Option to let Camel ignore unsupported charset in the local JVM when sending mails. If the charset is unsupported then {{charset=XXX}} (where {{XXX}} represents the unsupported charset) is removed from the {{content-type}} and it relies on the platform default instead. |
| {{sslContextParameters}} | {{null}} | *Camel 2.10:* Reference to a {{org.apache.camel.util.jsse.SSLContextParameters}} in the [Registry|http://camel.apache.org/registry.html].&nbsp; This reference overrides any configured SSLContextParameters at the component level.&nbsp; See [Using the JSSE Configuration Utility|http://camel.apache.org/http4.html#HTTP4-UsingtheJSSEConfigurationUtility]. |
| {{searchTerm}} | {{null}} | *Camel 2.11:* Refers to a {{javax.mail.search.SearchTerm}} which allows to filter mails based on search criteria such as subject, body, from, sent after a certain date etc. See further below for examples. |
| {{searchTerm.xxx}} | {{null}} | *Camel 2.11:* To configure search terms directly from the endpoint uri, which supports a limited number of terms defined by the {{org.apache.camel.component.mail.SimpleSearchTerm}} class. See further below for examples. | 
{div}

...

Programmatic configuration of the endpoint
Code Block

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(...)
&nbsp; &nbsp; .to("smtps://smtp.google.com?username=user@gmail.com&password=password&sslContextParameters=#sslContextParameters");
Spring DSL based configuration of endpoint
Code Block
xml
xml

...
<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&password=password&sslContextParameters=#sslContextParameters"/>...

...

In the sample code below, the email message is sent to davsclaus@apache.org, because it takes precedence over the pre-configured recipient, 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.

Code Block
java
java

        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("to", "davsclaus@apache.org");

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

...

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:

Code Block
java
java

        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("to", "davsclaus@apache.org ; jstrachan@apache.org ; ningjiang@apache.org");

...

For example, you define the following headers on the a Message:

Code Block

Map headers = new HashMap();
map.put("To", "Claus Ibsen <davsclaus@apache.org>");
map.put("From", "James Strachan <jstrachan@apache.org>");
map.put("Subject", "Camel is cool");

...

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.

Code Block

from("jms://queue:subscription").to("smtp://admin@mymailserver.com?password=secret");

In the next sample, we poll a mailbox for new emails once every minute. Notice that we use the special consumer option for setting the poll interval, consumer.delay, as 60000 milliseconds = 60 seconds.

Code Block

from("imap://admin@mymailserver.com
     password=secret&unseen=true&consumer.delay=60000")
    .to("seda://mails");

...

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 have extensive documentation on how to do this.

Code Block

from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD"
    + "&delete=false&unseen=true&consumer.delay=60000").to("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:

Code Block

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=[...

...

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:

Code Block

from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD"
    + "&delete=false&unseen=true&consumer.delay=60000").process(new MyMailProcessor());

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

Code Block

    public void process(Exchange exchange) throws Exception {
        // the API is a bit clunky so we need to loop
        Map<String, DataHandler> attachments = exchange.getIn().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();
            }
        }
   }

...

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

Code Block
xml
xml

<split>
  <method beanType="org.apache.camel.component.mail.SplitAttachmentsExpression"/>
  <to uri="mock:split"/>
</split>

...

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

Code Block
xml
xml

<route>
  <from uri="imaps://mymailseerver?username=foo&password=secret&searchTerm.subjectOrBody=Camel"/>
  <to uri="bean:myBean"/>
</route>

...

Or to get the new unseen emails going 24 hours back in time you can do. Notice the "now-24h" syntax. See the table below for more details.

Code Block
xml
xml

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

You can have multiple searchTerm in the endpoint uri configuration. They would then be combined together using AND operator, eg 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:

Code Block
xml
xml

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

...

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

Code Block

<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:

Code Block
xml
xml

<route>
  <from uri="imaps://mymailseerver?username=foo&password=secret&searchTerm=#mySearchTerm"/>
  <to uri="bean:myBean"/>
</route>

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

Code Block

// we just want the unseen mails which is 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();

Include Page
Endpoint See Also
Endpoint See Also