edit delete favorite
Posted by eric on Nov 28, 2007
Here is a Ruby program that I use to search my IMAP mailbox with combinations of search criteria. It is a mixture of several different Ruby-based approaches I found on the Internet for searching email systems.

Note that you don't need all the comments at the front as I've shown. It's just that I can't remember all the crazy flags that can be used, and at this time I'm not going to take the time to write a better mail system interface, although IMHO a better interface is surely needed.

Without any further ado, here is my Ruby source code that lets you search your email with powerful options/combinations:
require 'net/imap'

# mostly written by Al Alexander, http://DevDaily.com
# (okay, okay, i copied a lot of it and glued it together)

# ==========
# IMAP FLAGS
# ==========
# BEFORE <date>:  8-Aug-2002.
# BODY <string>:
# CC <string>:
# FROM <string>:
# NEW:  messages with the \Recent, but not the \Seen, flag set.
# NOT <search-key>:
# OR <search-key> <search-key>: "or" two search keys together.
# ON <date>:
# SINCE <date>:
# SUBJECT <string>:
# TO <string>:

# ===============
# ENVELOPE FIELDS
# ===============
# date:
# subject:
# from:     an array of Net::IMAP::Address
# sender:   an array of Net::IMAP::Address
# reply_to: an array of Net::IMAP::Address
# to:       an array of Net::IMAP::Address
# cc:       an array of Net::IMAP::Address
# bcc:      an array of Net::IMAP::Address

# ==============
# ADDRESS FIELDS
# ==============

# name:
# route:
# mailbox:
# host:

server = "MY-MAILSERVER"    # change this for your system
user = "MY-USERNAME"        # change this for your system
pass = "MY-PASSWORD"        # change this for your system
#folder = "INBOX.Sent"      # shows how to specify a different folder
folder = "INBOX"

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

# "SINCE", "1-Apr-2003"
#imap.search(["FROM", "ann", "NOT", "NEW", "SINCE", "1-Apr-2003", 
#             "BODY", "tree"]).each do |msg_id|
#imap.search(["TO", "reggie", "BODY", "vacation"]).each do |msg_id|

imap.search(["FROM", "fred", "BODY", "ssh").each do |msg_id|
  msg = imap.fetch(msg_id, "(UID RFC822.SIZE ENVELOPE BODY[TEXT])")[0]
  body = msg.attr["BODY[TEXT]"]
  puts "#{body}"

  #envelope = msg.attr["ENVELOPE"]
  #uid = msg.attr["UID"]
  #size = msg.attr["RFC822.SIZE"]
  #puts "To: #{to}"

  env = imap.fetch(msg_id, "ENVELOPE")[0].attr["ENVELOPE"]
  puts "#{env.from[0].name}: \t#{env.subject}"
end

imap.logout
imap.disconnect
 
Must be logged in to add a comment or review

Comments

Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Users
Spacer
Top Tags
Spacer