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.