1

Does anybody know how to get mail from an array of email addresses using the 'mail' gem in Ruby? I've seen the thread for getting unread messages like so:

new_messages = Mail.find(keys: ['NOT','SEEN'])

But I cannot find how to get messages from a certain address. I've tried:

new_messages = Mail.find(keys: ['FROM','example@hello.com'])

but it doesn't work.

I know section 6.4.4 of the IMAP protocol indicates the different search flags you can use to search for messages, but I can't seem to make it work.

Community
  • 1
  • 1

2 Answers2

1

Unfortunately, neither

Mail.find( keys: ['FROM', from_address] )

nor

Mail.find( keys: "FROM #{from_address}" )

worked. What worked, however, is quoting the email address:

Mail.find( keys: "FROM \"#{from_address}\”" )

Luckily, it was just the missing quotes, as the array variant works as well when quoting the email address:

Mail.find( keys: ['FROM', "\"#{from_address}\”"] )
crn
  • 323
  • 1
  • 2
  • 8
0

Try this for single email address

Mail.all.select { |mail| mail.from.addresses.include?('example@hello.com') }

And for multiple try this

addresses = ['example@hello.com', 'test@hello.com']
Mail.all.select { |mail| (addresses - mail.from.addresses).empty? } 

Also if you want to find just first mail try this

Mail.all.find { |mail| mail.from.addresses.include?('example@hello.com') }  
  • Thanks Amit - would this still be loading in all the messages first and then filtering them out? I'm trying to only search the actual inbox for the specified emails to keep things fast. –  Jul 16 '17 at 20:56