I am trying to check/filter through users inbox emails and check for keywords "offer" and "letter"
from calling messages on gmail api it returns the message id and threads which you can use to get the message contents that I have added to an array from my example below
def keyword_check
client = Signet::OAuth2::Client.new(access_token: session[:access_token])
service = Google::Apis::GmailV1::GmailService.new
service.authorization = client
messages = service.list_user_messages('me')
@messages_json = []
messages.messages.each do |m|
response = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages/#{m.id}?access_token=#{session[:access_token]}")
res = JSON.parse(response.body)
@messages_json << res
end
filter = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages?q=offer?access_token=#{session[:access_token]}")
mes = JSON.parse(filter.body)
render json: @messages_json.to_json
end
this returns all the messages in an array but I am finding it difficult filtering the array and checking for the particular keywords and returning both a boolean of true or false and the message itself alone in the array?
I think you should check whether the keywords are present in the response.body
before adding them to the array:
def keyword_check
client = Signet::OAuth2::Client.new(access_token: session[:access_token])
service = Google::Apis::GmailV1::GmailService.new
service.authorization = client
messages = service.list_user_messages('me')
@messages_json = []
messages.messages.each do |m|
response = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages/#{m.id}?access_token=#{session[:access_token]}")
res = JSON.parse(response.body)
@messages_json << res if matches_keywords(response.body)
end
filter = HTTParty.get("https://www.googleapis.com/gmail/v1/users/me/messages?q=offer?access_token=#{session[:access_token]}")
mes = JSON.parse(filter.body)
render json: @messages_json.to_json
end
def matches_keywords content
return true if content.include?('offer')
return true if content.include?('letter')
return false
end
Edit: Be aware that the body probably contains all the HTML formatting, css code etcetera... suppose for instance that there's a CSS rule with 'letter-spacing', the new function will always return true, so please check whether you are able to get the TEXT content instead. For this, have a look at the documentation for the Gmail API.
Another approach could be to use Kaminara (or equivalent) to really dive into the HTML structure, and only check the part that holds the actual text ( or some specific or something)