How to Read Your Email with the JavaMail API, Starring Gmail IMAP
Computer musicians are often accused of looking like they’re checking their email when they’re playing. (Occasionally, I have seen someone doing just that!) But I wanted to experiment with playing music by checking my email. Java is an easy way to do that; with the free JavaMail API (part of the Java platform), you can access just about any IMAP or POP account, even a secure one, like Gmail.
What you need
JavaMail API (part of the enterprise Java platform, but available for free to desktop Java users as well)
Get the download, refer to the JavaDocs for reference (note that if you’re not using Java 6, there’s an extra support download for the "JavaBeans Activation Framework" — don’t actually need to know what it does, but you will need it with earlier Java versions)
jGuru: Fundamentals of the JavaMail API: A decent step-by-step tutorial, though you may want to compare it to some of the sample code (installed to the "demo" folder when you install JavaMail) to see how this fits together in a completed example.
Connecting to your favorite email provider
The JavaMail API FAQ specifically addresses Gmail and Yahoo! Mail.
IMAP is more fun, because it allows access to folders other than the inbox. To connect to Gmail IMAP, you need to use the "imaps" protocol for a secure SSL connection, rather than plain "imap".
Accessing folders is a little wonky in Gmail. Aside from the Inbox, labels and folders are accessed like this: store.getFolder("[Gmail]/Spam").
Examples
It takes just a few lines to connect and retrieve some basic information about messages. I’ll post code examples soon.
It’s helpful to know something about the java.util.Date class. Specifically, if you want to compare sent dates or otherwise manipulate time, first use message.getSentDate(), then take that date information and use getTime() to translate into milliseconds.

subscribe
archives
links