Credit: John Wells
You want to connect to an IMAP server in order to read and manipulate the messages stored there.
net/imap.rb package, written by Shugo Maeda,
is part of Ruby's standard library, and provides a very capable base
on which to build an IMAP-oriented email application. In the following
sections, I'll walk you through various ways of using this API to
interact with an IMAP server.
For this recipe, let's assume you have access to an IMAP server running at mail.myhost.com on the standard IMAP port 143. Your username is, conveniently, "username", and your password is "password".
To make the initial connection to the server, it's as simple as:
require 'net/imap' conn = Net::IMAP.new('mail.myhost.com', 143) conn.login('username', 'password')
Assuming no error messages were received, you now have a
connection to the IMAP server. The
Net::IMAP object puts all the capabilities
of IMAP at your fingertips.
Before doing anything, though, you must tell the server which
mailbox you're interested in working with. On most IMAP servers, your
default mailbox is called "INBOX". You can change mailboxes with
conn.examine('INBOX') # Use Net::IMAP#select instead for read-only access
A search provides a good example of how a
Net::IMAP object lets you interact with the
server. To search for all messages in the selected mailbox from a
particular address, you can use this code:
conn.search(['FROM', 'email@example.com']).each ...