1

I revised the demonstrated CreateMessageWithAttachment Python codes on Users.messages: send. The only difference is that I return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode("UTF-8")} instead of {'raw': base64.urlsafe_b64encode(message.as_string())} because the latter is actually causing errors.

After that, I tried to send myself an email with an attachment:

userID = my_email_address
API_KEY = my_api_key
# my_api_key was generated under my_email_address on GCP

email_content = CreateMessageWithAttachment(userID, userID, "Test API", "This is a test.", file_dir, filename)
r = requests.post(
    url="https://www.googleapis.com/gmail/v1/users/{}/messages/send?key={}".format(userID, API_KEY),
    data=json.dumps(email_content)
)

if r.status_code == 200:
    print("Succeed!")
else:
    print(r.status_code)

I am getting 401 as status code now, which seems like an authorization issue. However, I have no idea where to start to solve this problem. I am sure the API key is correct and it is permitted to call Gmail API.

One similar question on SO is How to access a gmail account I own using Gmail API?, but as a local cronjob, I don't know how to "Register my App at Google" like the answer suggested.

ytu
  • 1,822
  • 3
  • 19
  • 42
  • For example, how about using OAuth2 or service account? Because POST and PUT methods cannot be used by API key, while GET method can be used by it. Is your issue related to this situation? – Tanaike Oct 07 '18 at 23:06
  • @Tanaike Thank you. I'm not familiar with OAuth2, but I think POST methods _can_ be used by API key. That works on Google Cloud Vision API at least. – ytu Oct 08 '18 at 03:09
  • Thank you for replying. In my environment, I could confirm that ``gmail.users.messages.send`` works using OAuth2 while it doesn't work using the API key. When the API key is used, the error of ``"message": "Login Required"`` occurs. If this result was different from that at your environment, I'm sorry. – Tanaike Oct 08 '18 at 05:27

0 Answers0