Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
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
self[/#{Regexp.escape(marker1)}(.*?)#{Regexp.escape(marker2)}/m, 1]
# Add your credentials.
imap_server = ''
imap_username = ''
imap_password = 'psswd'
imap =, 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 =['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)
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