A Scala IMAP email client (using SSL, IMAPS, JavaMail)

If you ever need to write an IMAP client in Scala, I hope the following example can be helpful. For my project named SARAH (a Mac OS X Siri-like project), I wanted an IMAP client to periodically check my mail and then say something a little better than, "You've got mail", and the first part of that was getting a Scala IMAP client going.

Here then is the source code for a simple Scala IMAP client. It's important to note that this client runs under SSL (see the "imaps" part of the code). It also shows a Yahoo IMAP server/host, but I tested it against Gmail, and it works just fine there as well.

package scalamail

import javax.mail._
import javax.mail.internet._
import javax.mail.search._
import java.util.Properties

object ScalaImapSsl {

  def main(args: Array[String]) {
    val props = System.getProperties()
    props.setProperty("mail.store.protocol", "imaps")
    val session = Session.getDefaultInstance(props, null)
    val store = session.getStore("imaps")
    try {
      // use imap.gmail.com for gmail
      store.connect("imap.mail.yahoo.com", "<al@yahoo.com>", "password")
      val inbox = store.getFolder("Inbox")
      // limit this to 20 message during testing
      val messages = inbox.getMessages()
      val limit = 20
      var count = 0
      for (message <- messages) {
        count = count + 1
        if (count > limit) System.exit(0)
    } catch {
      case e: NoSuchProviderException =>  e.printStackTrace()
      case me: MessagingException =>      me.printStackTrace()
    } finally {

To use this object in your own code, just replace the fields in these two lines of code to match your email server, username, password, and mailbox name:

store.connect("imap.mail.yahoo.com", "username@yahoo.com", "password")
val inbox = store.getFolder("Inbox")

Another important note is that if you're using the Java J2SE distribution, you'll need to download the JavaMail API library. This is included in the J2EE distribution, but it's not in the J2SE SDK, so you'll need to download it separately.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.