Ruby mail example program - how to move IMAP email messages I've already read

Here's a Ruby mail program that I use to read my inbox, and move mail messages from a group of people that I have read to an IMAP folder that I have setup specifically for those people. The beauty of this is that I don't move the email messages I haven't read yet -- I just move the messages I have read.

For example, let's say that I get a lot of messages from an organization named "ACME, Inc.", and their domain is acme.com. I always want to see messages from this organization that I haven't read yet, but I'm okay with moving messages that I have already seen at least once to an IMAP folder named INBOX.acme.

I've written this Ruby mail/IMAP program just to handle this situation.

Ruby mail program

Here's the source code for my Ruby IMAP program. I've changed a few things in the interest of national security, but generally everything here is exactly as I run it.

require 'net/imap'

# ----- MODIFY THE NEXT 5 LINES -----
USERNAME='myUsername'
PASSWORD='myPassword'
MAIL_SERVER='myMailserver'
SOURCE_MAILBOX='INBOX' 
TARGET_MAILBOX='INBOX.acme' 

imap = Net::IMAP.new(MAIL_SERVER)
imap.authenticate('LOGIN', USERNAME, PASSWORD)
imap.select(SOURCE_MAILBOX)

count = 0

# i specify who the emails are from here. i also specify a "since" date, as that seems to limit
# my query and run faster.
# ----- MODIFY THIS SEARCH CRITERIA -----
imap.search(["FROM", "acme.com", "SEEN", "SINCE", "30-Sep-2006"]).each do |message_id|
  count = count + 1
  env = imap.fetch(message_id, "ENVELOPE")[0].attr["ENVELOPE"]
  puts "#{env.from[0].name}: \t#{env.subject}"
  imap.copy(message_id, TARGET_MAILBOX)
  imap.store(message_id, "+FLAGS", [:Deleted])
end
imap.expunge

puts "moved #{count} messages"

imap.logout
imap.disconnect

Ruby mail program - discussion

As you can see there are several variables that you need to modify to run this Ruby program, including the mail server and IMAP properties at the top of the script, and the search criteria shown later in the script.

Also note that as programs go, this one is dangerous. You really (really!) want to make sure that you get your variables and search criteria correct, as you will be moving email messages from IMAP one folder to another. I strongly recommend testing this program before running it live. A good way to test it is by commenting out the lines that begin with imap.copy, imap.store, and imap.expunge. Verify for yourself that everything looks okay, then use a date range to limit your risk, etc.

I run this program nightly using cron/crontab, so that when I come in the next morning I still see all the messages I haven't read yet, as well as all new messages I've received.