Technipelago AB

Technipelago Blog Stuff that we learned...


Reading IMAP mailbox with Groovy

Publicerad den 15 Mar 2009

Groovy can make it easy to read an IMAP mailbox

The following Groovy code connects to an IMAP mailbox and read all unread messages.


import javax.mail.*
import javax.mail.search.*
import java.util.Properties

Properties props = new Properties()
props.setProperty("mail.store.protocol", "imap")
props.setProperty("mail.imap.host", host)
props.setProperty("mail.imap.port", port)
def session = Session.getDefaultInstance(props, null)
def store = session.getStore("imap")
def inbox

try {
  store.connect(host, username, password)
  inbox = openFolder(store, "INBOX")
  def messages = inbox.search(
    new FlagTerm(new Flags(Flags.Flag.DELETED), false))
  messages.each { msg ->
    println("${msg.subject} ${msg.sender}")
    msg.setFlag(Flags.Flag.SEEN, true)
  }
} finally {
  if(inbox) {
    inbox.close(true)
  }
  store.close()
}

Tags: groovy email imap


« Back