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:

#
# DevDaily.com
# 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 mail.foo.com)"
user = "YOUR LOGIN NAME HERE"
pass = "YOUR PASSWORD HERE"
folder = "INBOX"

imap = Net::IMAP.new(server)
imap.login(user, pass)
imap.select(folder)

addrs = Set.new
imap.search(["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}"
  addrs.add(from)
end

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

imap.logout
imap.disconnect

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) president@whitehouse.gov"
  • 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