Posted in Scala

Receiving Mail in Scala

On recent project I had the need to read emails from my app so I thought I’d share a sample. This problem fits neatly into the construct of an Akka Actor.

import javax.mail.internet.MimeMessage
import javax.mail.{Folder, MessagingException, NoSuchProviderException, Session}

import actor.MailReceiverActor.Check
import akka.actor.{Props, Actor}

class MailReceiverActor(host: String, port: Int, user: String, password: String, inboxName: String) extends Actor {

  override def receive: Receive = {
    case Check =>
      val props = System.getProperties
      props.setProperty("mail.store.protocol", "imaps")
      val session = Session.getDefaultInstance(props, null)
      val store = session.getStore("imaps")
      try {
        store.connect(host, port, user, password)
        val inbox = store.getFolder(inboxName)
        inbox.open(Folder.READ_ONLY)
        inbox.getMessages map {
          case message:MimeMessage => processMessage(message) // define this function to handle the message
          case _ => // do nothing or log that you only process MimeMessages
        }
        inbox.close(true)
      } catch {
        case e @ (_:NoSuchProviderException|_:MessagingException) => // log the error
      } finally {
        store.close()
      }
  }
}

object MailReceiverActor {
  case object Check

  def props(host:String, port:Int, user:String, password:String, inboxName:String) = {
    Props(new MailReceiverActor(host, port, user, password, inboxName))
  }

}

Then to use this Actor you can just create a schedule for how often the mail will be checked. In play you can place this in the onStart of Global.

val system = Akka.system(app)
val mailActor = system.actorOf(MailReceiverActor.props(host, userId, user, password, inboxName))

implicit val executionContext = // user defined or use the default play context
system.scheduler.schedule(5.seconds, 20.minutes, mailActor, MailReceiverActor.Check)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s