0
votes

iam using gmail api, in my rails application to send emails. a user can authenticate to google and send emails(it will ask for user consent. upon user approval he can send emails from his account)

my requirement is i want to show the logined user, how many emails sent from his email id in my rails app. for that im using using the below end point. but im getting an error

require 'net/http'
require 'uri'

in controler

def sent_email_count
_
    api_key = "api_key_contains_smal_case_capital_case_letters_and_special_symbols"
     uri = URI.parse("https://www.googleapis.com/gmail/v1/users/#{current_user.email}/messages?labelIds=SENT&q=newer_than%3A1d&key={api_key}")
     @gmail_response = Net::HTTP.get_response(uri)

end

in views :-

response <%= @gmail_response >

but getting unauthorized error.

sent email count :- #Net::HTTPUnauthorized:0x00007f6f5e3e2158

i tried like below also. but its not working.(string interpoltion changes for api key)

uri = URI.parse("https://www.googleapis.com/gmail/v1/users/#{current_user.email}/messages?labelIds=SENT&q=newer_than%3A1d&key=#{api_key}")
     @gmail_response = Net::HTTP.get_response(uri)
     
     
uri = URI.parse("https://www.googleapis.com/gmail/v1/users/#{current_user.email}/messages?labelIds=SENT&q=newer_than%3A1d&key=api_key")
     @gmail_response = Net::HTTP.get_response(uri)

can some one help me with this

1
Consent to send an email doesn't necessarily grant permission to query the user's account data. I'd check the gmail api and see what permissions are required. Alternatively, you could record the emails sent via your application in a database table.dbugger

1 Answers

0
votes

Answer

You are missing the token in your code, that's why your requests are HTTP 401 Unauthorized, I strongly recommend you to use the Official documentation Quickstart In your case, you should use the list_user_messages method.

First of all list all the messages using the q parameter as in:sent which means read all the sent messages from my Gmail and then count your array of messages. Here's an example:

# ...
# Previous quickstart code

user_id = "[email protected]"
result = service.list_user_messages(user_id=user_id, q="in:sent")
puts "count : #{result.messages.length()}\n\n"

Reference

Ruby Google API Client

Method: users.messages.list