Mail Component
The mail component provides access to Email via Spring's Mail support and the underlying JavaMail system.
 | Classpath issue
If you have trouble with sending mails that for instance doesn't contain any subject, has wrong recipients or other unforeseen errors then it could be because of having geronimo-javamail_1.4_spec-1.3.jar in the classpath. This was the culprit in a long bug hunt reported in CAMEL-869 . |
 | Geronimo mail .jar
We have discovered that the geronimo mail .jar (v1.6) have a bug when polling mails with attachments. It cannot correctly identify Content-Type. So if you attach a jepg file to a mail and you poll it then the Content-Type is resolved as text/plain and not as image/jpeg. For that reason we have added a org.apache.camel.component.ContentTypeResolver SPI interface where you can provide your own implementation and fix this by returning the correct mime type based on the file name. So if the file name ends with jpeg/jpg you can return image/jpeg.
You can set your custom resolver on the MailComponent or the MailEndpoint. This feature is added in Camel 1.6.2/2.0. |
 | POP3 or IMAP
POP3 has some limitations and end users is encouraged to use IMAP if possible. |
URI format
which supports either POP, IMAP or SMTP underlying protocols.
It is possible to omit the user-info and specify the username as a URI parameter instead
Such as:
SSL support
Camel have support for secure mail protocols. Just add a s to the scheme such as:
 | SSL Information
Its the underlying mail framework that is handling the SSL support. Camel uses SUN JavaMail. However SUN JavaMail only trusts certificates issued by well known Certificate Authorities. So if you have issued your own certificate you have to import it into the local Java keystore file (see SSLNOTES.txt in JavaMail for details).
If you are using your own signed certificates sometimes it can be cumbersome to install your certificate in the local keystore. Camel provides a test option dummyTrustManager that when enabled will accept any given certificate.
Notice: this is strongly discouraged not using in production environments. |
Default Ports
As of Camel 1.4 support for default port number has been added. If the port number is omitted Camel will determine based on the protocol the port number to use.
| Protocol |
Default Port Number |
| SMPT |
25 |
| SMPTS |
465 |
| POP3 |
110 |
| POP3S |
995 |
| IMAP |
143 |
| IMAPS |
993 |
Options
| Property |
Default |
Description |
| host |
|
The host name or IP address to connect to |
| port |
See Default Ports |
The TCP port number to connect on |
| user-info |
|
The user name on the email server |
| username |
|
The user name on the email server configured as a URI parameter |
| password |
null |
The users password to use, can be omitted if the mail server does not require a password |
| ignoreUriScheme |
false |
If disabled Camel will use the scheme to determine the transport protocol to use (pop, imap, smtp etc.) |
| defaultEncoding |
null |
The default encoding to use for MineMessages |
| contentType |
text/plain |
New option in Camel 1.5. The mail message content type. Use text/html for html mails. |
| folderName |
INBOX |
The folder to poll |
| destination |
user-info@host |
@deprecated use To option. The TO recipients (the receivers of the mail) |
| to |
user-info@host |
The TO recipients (the receivers of the mail). This option is introduced in Camel 1.4. |
| CC |
null |
The CC recipients (the receivers of the mail). This option is introduced in Camel 1.4. |
| BCC |
null |
The BCC recipients (the receivers of the mail). This option is introduced in Camel 1.4. |
| from |
camel@localhost |
The FROM email address |
| deleteProcessedMessages |
true/false |
Deletes the messages after they have been processed. This is done by setting the DELETED flag on the mail message. If false then the flag SEEN is set instead. As of Camel 1.5 the default setting is now false. |
| delete |
false |
Camel 2.0: Deletes the messages after they have been processed. This is done by setting the DELETED flag on the mail message. If false then the flag SEEN is set instead. |
| processOnlyUnseenMessages |
false/true |
As of Camel 1.4 its possible to configure MailConsumer to only process unseen messages (eg new messages) or all. Note Camel will always skip deleted messages. Setting this option to true will filter to only unseen messages. As of Camel 1.5 the default setting is now true. POP3 does not support the SEEN flag so this option is not supported using POP3, instead use IMAP. |
| unseen |
true |
Camel 2.0: Is used to only fetch unseen messages (eg new messages). Note: POP3 does not support the SEEN flag, instead use IMAP. |
| fetchSize |
-1 |
As of Camel 1.4 a maximum number of messages to consume during a polling can be set. This can be used to not exhaust 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. |
| alternateBodyHeader |
mail_alternateBody |
Camel 1.6.1: This is a key to lookup in the IN message headers for an alternative mail. If you for instance send text/html mails and also want to provide an alternative mail body for non html email clients then set the alternative mail body with this key as a header. This option has been renamed in Camel 2.0 to alternativeBodyHeader. |
| alternativeBodyHeader |
CamelMailAlternativeBody |
Camel 2.0: This is a key to lookup in the IN message headers for an alternative mail. If you for instance send text/html mails and also want to provide an alternative mail body for non html email clients then set the alternative mail body with this key as a header. |
| debugMode |
false |
As of Camel 1.4 its possible to enable the debug mode on the underlying mail framework. SUN Mail framework will default output to System.out. |
| connectionTimeout |
30000 |
As of Camel 1.4 the connection timeout can be configured in millis. Default is 30 seconds. |
| dummyTrustManager |
false |
As of Camel 1.4 testing SSL connections can be easier if enabling a dummy TrustManager that trust any given certificate. Notice this is only to be used for testing, as it does not provide any security at all. |
| consumer.initialDelay |
1000 |
Millis before the polling starts |
| consumer.delay |
60000 |
As of Camel 1.4 the default consumer delay is now 60 seconds. Camel will therefore only poll the mailbox once a minute to not exhaust the mail server. The default value in Camel 1.3 is 500 millis. |
| consumer.useFixedDelay |
false |
true to use fixed delay between pools, otherwise fixed rate is used. See ScheduledExecutorService in JDK for details. |
| mail.XXX |
null |
As of Camel 2.0 you can set any additional java mail properties . 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, such as: mail.pop3.forgettopheaders=true&mail.mime.encodefilename=true. |
| maxMessagesPerPoll |
0 |
Camel 2.0: An integer to define a maximum messages to gather per poll. By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. Set a value of 0 or negative to disabled it. |
| javaMailSender |
null |
Camel 2.0: Pluggable org.springframework.mail.javamail.JavaMailSender to use a custom implementation for sending mails. If none provided Camel uses the default org.springframework.mail.javamail.JavaMailSenderImpl. |
Defaults changed in Camel 1.4
As of Camel 1.4 the default consumer delay is now 60 seconds. Camel will therefore only poll the mailbox once a minute to not exhaust the mail server. The default value in Camel 1.3 is 500 millis.
Defaults changed in Camel 1.5
In Camel 1.5 the following default options has changed:
- deleteProcessedMessages is now false as we felt Camel should not delete mails on the mail server by default.
- processOnlyUnseenMessages is now true as we felt Camel should only poll new mails by default.
Mail Message Content
Camel will use the Exchange Message IN body as the MimeMessage
text content. The body is converted to String.class.
Camel copies all the Exchange Message 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:);
The same applies for other MimeMessage headers such as recipients, so you can use a header property as the TO:
Map map = new HashMap();
map.put("To", "davsclaus@...");
map.put("From", "jstrachan@...");
map.put("Subject", "Camel rocks");
String body = "Hello Claus.\nYes it does.\n\nRegards James.";
template.sendBodyAndHeaders("smtp:, body, map);
Headers take precedence over pre configured recipeients
From Camel 1.5 onwards the recipients from the message headers will always take precedence over any pre configured. The idea is that if you provide any recipients in the message headers then its what you get (WYSIWYG). The pre configuration is just there for fallback or if you use fixed recipients.
In the sample code below the mail is sent to davsclaus@... since it will take precedence over the pre configured. Even if we have CC pre configured they will not recieve the mail. The headers is all or nothing, it will not mix and match between headers and pre configured. You either get one or the other.
Map<String, Object> headers = new HashMap<String, Object>();
headers.put("to", "davsclaus@...");
template.sendBodyAndHeaders("smtp:, "Hello World", headers);
Multiple recipients easier configuration
Also new in Camel 1.5 is the possibility to set multiple recipients in a single String parameter. This applied to both the headers and pre configuration.
In the sample above we use semi colon as separators. Camel support both semicolon = ; and comma = , as separator char.
Setting sender name and email
You can provide the recipients in the format "name <email>" to include both the name and the email.
For example you can provide the following headers on the Message:
Map headers = new HashMap();
map.put("To", "Claus Ibsen <davsclaus@...>");
map.put("From", "James Strachan <jstrachan@...>");
map.put("Subject", "Camel is cool");
SUN JavaMail
SUN JavaMail
is used under the covers for consuming and producing mails.
We encourage end-users to consult these links when using either POP3 or IMAP protocol. Notice that especially POP3 have limited features compared to IMAP.
Samples
We start with a simple route that sends the messages received from a JMS queue as emails. The email account with be the admin account on mymailserver.com.
from("jms:).to("smtp://admin@...?password=secret");
In the next sample we will poll a mailbox for new emails once every minute. Notice that we use the special consumer parameter for setting the poll interval consumer.delay as 60000 millis = 60 seconds.
from("imap:).to("seda://mails");
In this sample we want to send a mail to multiple recipients. This feature was introduced in camel 1.4.
Sending mail with attachment sample
 | Attachments in not support by all Camel components
The Attachments API is from the Java Activation Framework and is generally only used by the Mail API. Thus many of the other Camel components does not support the attachments and thus you could potential end up with loosing your attachments. So the rule of thumb is to add the attachments just before sending the message to the mail endpoint. |
Attachments is a new feature in Camel 1.4 that of course is also supported by the mail component. In the sample below we send a mail message containing a plain text message with a logo file attachment.
Endpoint endpoint = context.getEndpoint("smtp:);
Exchange exchange = endpoint.createExchange();
Message in = exchange.getIn();
in.setBody("Hello World");
in.addAttachment("logo.jpeg", new DataHandler(new FileDataSource("src/test/data/logo.jpeg")));
Producer producer = endpoint.createProducer();
producer.start();
producer.process(exchange);
SSL sample
In this sample we want to poll our Google mail inbox for mails. Google mail requires to use SSL and have it configured for other clients to access your mailbox. This is done by logging into your google mail and change your settings to allow IMAP access. Google have extensive documentation how to do this.
from("imaps:
+ "&deleteProcessedMessages=false&processOnlyUnseenMessages=true&consumer.delay=60000").to("log:newmail");
The route above will poll the google mail inbox for new mails once every minute and log it 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 imaps2008-05-08 06:32:11,203 DEBUG MailConsumer - Polling mailfolder: imaps2008-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@...>], to=YOUR_USERNAME@...], subject=[...
2008-05-08 06:32:12,187 INFO newmail - Exchange[MailMessage: messageNumber=[332], from=[James Bond <007@...>], to=YOUR_USERNAME@...], subject=[...
SSL sample with dummyTrustManager
In the next sample we want to sent mails from Camel using our own mail server using secure connections. As our own mail server is using our own signed certificate we need either to
- install our certificate in the local keystore Camel uses
- use the dummyTrustManager option for testing purpose to see if the secure communication works
In the sample we use the dummyTrustManager option:
from("seda:mailsToSend").to("imaps:);
Consuming mails with attachment sample
In this sample we poll a mailbox and want to store all attachments from the mails as files. First we define our 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:
+ "&deleteProcessedMessages=false&processOnlyUnseenMessages=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:
public void process(Exchange exchange) throws Exception {
Map<String, DataHandler> attachments = exchange.getIn().getAttachments();
if (attacments.size() > 0) {
for (String name : attachments.keySet()) {
DataHandler dh = attachments.get(name);
String filename = dh.getName();
byte[] data = exchange.getContext().getTypeConverter().convertTo(byte[].class, dh.getInputStream());
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.
See Also