Ruby mail - find all unique email addresses in your inbox

Here's a sample Ruby mail program that I created that finds and prints all of the unique email addresses in my IMAP inbox. Hopefully the source code is readable enough that it doesn't need much description. The only hard part is trying to figure out how to get the email address from the Envelope, and that's only because the documentation is hard to find.

Ruby mail program

Here's my Ruby IMAP mail program source code:

# A Ruby program to find and print all the unique email addresses 
# in your inbox.
require 'net/imap'
require 'set'

server = "YOUR MAIL SERVER HERE (like"
folder = "INBOX"

imap =
imap.login(user, pass)

addrs =["SINCE", "1-Jan-2005"]).each do |msg_id|
  env = imap.fetch(msg_id, "ENVELOPE")[0].attr["ENVELOPE"]
  name    = env.from[0].name
  mailbox = env.from[0].mailbox
  host    = env.from[0].host
  from = "(#{name}) #{mailbox}@#{host}"

# print 'em
addrs.sort.each { |a|
  puts a


Ruby mail program - discussion

As you can (hopefully) see from the source code this Ruby program does the following:

  • Opens an IMAP connection to your mail server.
  • Does a search and finds all messages in your inbox that have arrived since 1/1/2005.
  • Creates an output String named from that looks like this:
    "(Hillary Clinton)"
  • Adds each "from" string to a Set named addrs.
  • Prints every string in the addrs set.
  • Disconnects from the IMAP server.

Here are a few URLs that were important in learning how to create an address from the information in the Envelope class:

  1. Net::IMAP::Envelope
  2. Net::IMAP::Address
  3. Net::IMAP