Skip to content

Instantly share code, notes, and snippets.

@tsrivishnu
Last active August 29, 2015 14:16
Show Gist options
  • Save tsrivishnu/6f2f58efe87785848366 to your computer and use it in GitHub Desktop.
Save tsrivishnu/6f2f58efe87785848366 to your computer and use it in GitHub Desktop.
Check unique "from" addresses in an IMAP mailbox.
#!/usr/bin/env ruby
require 'net/imap'
class String
def string_between_markers marker1, marker2
# Code snippet from http://stackoverflow.com/a/9661504/976880
self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1]
end
end
# Add your credentials.
imap_server = 'mail.example.com'
imap_username = 'user@example.com'
imap_password = 'psswd'
imap = ::Net::IMAP.new(imap_server, 993, true)
imap.authenticate('PLAIN', imap_username, imap_password)
# Change to any mailbox of your account.
imap.examine('INBOX') # Use 'examine' istead of 'select' to preserve recent mails
all_seqnos = imap.search(['ALL']) # replace 'ALL' with 'RECENT' to get only recent mails.
from_emails = []
imap.fetch(all_seqnos.first..all_seqnos.last, "BODY[HEADER.FIELDS (FROM)]").each do |str|
from_email = str.attr['BODY[HEADER.FIELDS (FROM)]'].string_between_markers("From: ", "\r\n\r\n")
from_emails << from_email if !from_emails.include?(from_email)
end
puts "Processed #{all_seqnos.count} messages\n\n"
puts "Services from which the messages are received: "
puts from_emails
puts "\n"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment