Thursday, February 24, 2011

Processing incoming emails with Spring Integration

Recently, I had a task to automatically process emails that come to specified address. Trivial solution is to create some periodic task with Quartz or Timer and pull new emails and process them. I googled if there is ready lib to do this and found that this can be done with Spring; or more specifically with Spring Integration. I heard about this project, but didn't payed a lot of attention to it. Main idea behind it is - this is small local ESB, so basically if you need to act on some incoming event or send some outgoing event to some system, this is nice place to look at. Another good thing is that it provides easy and out-of-the-box ready interface to many different systems, which is exactly what I was looking for email processing.
So with Spring Integration, reading email is just few beans definition (in Grails Spring DSL):


  integration.channel(id:'inboundEmailChannel')

  mail.'inbound-channel-adapter'(id:"imapAdapter",
      'store-uri':"imaps://${CH.config.logging.imap.credentials}@imap.gmail.com/INBOX",
      'java-mail-properties':['mail.imap.socketFactory.class':'javax.net.ssl.SSLSocketFactory',
            'mail.imap.socketFactory.fallback':false,
             'mail.store.protocol':'imaps', 'mail.debug':false],
      channel:"inboundEmailChannel",
      'should-delete-messages':true,
      'should-mark-messages-as-read':true,
      'auto-startup':true) {
          integration.poller('max-messages-per-poll':"1", 'fixed-rate':"5000")
   }

   integration.'service-activator'( 'input-channel':"inboundEmailChannel",
                ref:"emailService", method:"inboundEmail")


So, with this, when you have incoming email, it will call inboundEmail method of emailService.

No comments:

Post a Comment