Katie H
Katie H

Reputation: 2293

Searching for multiple labels Gmail API - Rails

I am using this gem in my rails app to interact with the Gmail API: https://github.com/gmailgem/gmail

I am able to search for emails containing one label:

require 'gmail'
gmail = Gmail.connect("[email protected]", "testpwd")
gmail.mailbox('Urgent')

But when I try to search for multiple labels, I get an error. How do I find all email that contain two specific labels, such as email that contain both the label "Urgent" and "Priority"?

Upvotes: 0

Views: 321

Answers (2)

Paul Verschoor
Paul Verschoor

Reputation: 1559

The gmail gem let's you use the Google search filter, like this:

gmail.mailbox('Urgent').emails(gm: 'label:'Priority')

Upvotes: 0

SteveTurczyn
SteveTurczyn

Reputation: 36880

You could try using intersection...

urgent_priority_emails = gmail.mailbox('Urgent').emails & gmail.mailbox('Priority').emails

However, I have a recollection that this may not work, because the emails are treated as different objects even though they are the same messages.

An alternative that may work...

   urgent_email_message_ids = gmail.mailbox('Urgent').emails.map{|email|email.message_id}
   urgent_priority_emails = gmail.mailbox('Priority').emails.select{|email| urgent_email_message_ids.include?(email.message_id)}

Upvotes: 3

Related Questions