Friday, 5 August 2011

Apache Camel and SubEthaSMTP

There are times, having or relying on more than one set of library to do your bidding can be very helpful to streamline and simplify your projects. One example is, although Apache Camel has very powerful integration capabilities, there are times that you might want to do further processing using other libraries to get the benefits of encapsulating changes from your possibly already complicated rules in Apache Camel.

One such example is sending out information to users. You might opt to say, use Apache Camel to send out mails, but instead of to a typical SMTP Server, send it to SubEtha SMTP, which is purely a JAVA library that receives email and pass it to your handler for further processing. It will not be storing or even doing the actual mail delivery. An excerpt from their website (with link to their project)

SubEtha SMTP is a Java library which allows your application to receive SMTP mail with a simple, easy-to-understand API.

Typical interesting scenarios you might want to use this:
  • perform filtering on the sender and recipient to weed out inactive or barred users
  • log email messages to files or database
  • instead of sending mail, lookup recipient preference and optionally send via other channels such as IM (Instant Messaging) or SMS.
  • Configure multi-channel send, e.g. Send email to recipient(s), and send notification to them via IM or SMS to inform them about the email header and sender, e.g. You have a mail from - "Automated Backup for Server BBIGGG completed successfully"
  • Analytics or Statistics to determine how many emails are sent to a specific recipient, and how many emails with a particular subject is sent.
 Using SubEtha SMTP is simple, all you need to do is to assign a MessageHandlerFactory to its constructor, which is responsible in creating MessageHandlers to handle incoming mails. A simple example is below:

1: SMTPServer server = new SMTPServer(new MyMessageHandlerFactory());
2: server.setMaxConnections(100);
3: AuthenticationHandlerFactory fact = new
     LoginAuthenticationHandlerFactory( new Validator() );
4: server.setAuthenticationHandlerFactory(fact);
5: server.start();
Line 1 is used to associate your message handler factory (which implements the: org.subethamail.smtp.MessageHandlerFactory interface).

Line 2, which is optional, can be used to set maximum number of connections

Line 3 and 4 are use to setup authentication handlers, in case you would like to authenticate incoming connections.

Line 5 is used to start the server.

In version 3.1.6 of the library, it comes with two higher-level interface and adapter to help to ease construction of your Message Handler, which are the SimpleMessageListener and SmarterMessageListener.

That's all for a start. I'll try to write a more complete example in my next article.

Enjoy processing emails!

No comments:

Post a Comment