Since Camel 1.0
Both producer and consumer are supported
The Mail component provides access to Email via Spring’s Mail support and the underlying JavaMail system.
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>
Tip
|
POP3 or IMAP POP3 has some limitations and end users are encouraged to use IMAP if possible. |
Note
|
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. |
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]
Typically, you specify a URI with login credentials as follows:
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
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 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
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.
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
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&password=password&sslContextParameters=#sslContextParameters"/>...
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).
Camel uses the message exchange’s IN body as the
MimeMessage
text content. The body is converted to String.class
.
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 code below demonstrates this:
from("direct:a").setHeader("subject", constant(subject)).to("smtp://james2@localhost");
The same applies for other MimeMessage headers such as recipients, so
you can use a header property as To
:
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", 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.
The recipients specified in the message headers always 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 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.
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:
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.
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:
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 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.
-
And generally about the MAIL Flags
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.
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
.
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.
from("imap://admin@mymailserver.com?password=secret&unseen=true&delay=60000")
.to("seda://mails");
Warning
|
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.
// 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);
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.
from("imaps://imap.gmail.com?username=YOUR_USERNAME@gmail.com&password=YOUR_PASSWORD"
+ "&delete=false&unseen=true&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:
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:
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:
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.
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
<split>
<method beanType="org.apache.camel.component.mail.SplitAttachmentsExpression"/>
<to uri="mock:split"/>
</split>
You can also split the attachments as byte[] to be stored as the message body. This is done by creating the expression with boolean true
SplitAttachmentsExpression split = SplitAttachmentsExpression(true);
And then use the expression with the splitter EIP.
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:
<route>
<from uri="imaps://mymailseerver?username=foo&password=secret&searchTerm.subjectOrBody=Camel"/>
<to uri="bean:myBean"/>
</route>
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. See the table below for more details.
<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 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:
<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
<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:
<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
SearchTerms
using the org.apache.camel.component.mail.SearchTermBuilder
class. This allows you to build complex terms such as:
// 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();
When sending mails, then you can provide dynamic java mail properties for the JavaMailSender
from
the Exchange as message headers with keys starting with java.smtp.
.
You can set any of the java.smtp
properties which you can find in the Java Mail documentation.
For example, to provide a dynamic uuid in java.smtp.from
(SMTP MAIL command):
.setHeader("from", constant("reply2me@foo.com"));
.setHeader("java.smtp.from", method(UUID.class, "randomUUID"));
.to("smtp://mymailserver:1234");
Note
|
This is only supported when not using a custom JavaMailSender .
|
spring-boot:partial$starter.adoc