Is it possible to use the Python requests library to send Gmail only using the Google Gmail API? I am trying to send Gmail with a python request library. But it ends up with an error 401. I want to know what is the proper way to send Gmail with Google Gmail API.
JavaScript
x
57
57
1
import sys
2
import requests
3
import base64
4
import sys
5
from email.mime.text import MIMEText
6
7
AccessToken = ""
8
9
params = {
10
"grant_type": "refresh_token",
11
"client_id": "xxxxxxxxxxxxxxx",
12
"client_secret": "xxxxxxxxxxxxxxx",
13
"refresh_token": "xxxxxxxxxxxxxxxxxxxx",
14
}
15
16
authorization_url = "https://www.googleapis.com/oauth2/v4/token"
17
18
r = requests.post(authorization_url, data=params)
19
20
if r.ok:
21
AccessToken = str((r.json()['access_token']))
22
23
EmailFrom = "Test1@gmail.com"
24
EmailTo = "test2@gmail.com"
25
26
def create_message(sender, to, subject, message_text):
27
28
message = MIMEText(message_text, 'html')
29
message['to'] = to
30
message['from'] = sender
31
message['subject'] = subject
32
raw = base64.urlsafe_b64encode(message.as_bytes())
33
raw = raw.decode()
34
body = {'raw': raw}
35
return body
36
37
38
body = create_message(EmailFrom, EmailTo, "Just wanna Say Waka Waka!", "Waka Waka!")
39
40
41
url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"
42
43
header = {
44
'Authorization': 'Bearer ' + AccessToken,
45
'Content-Type': 'application/json',
46
'Accept': 'application/json'
47
}
48
49
r = requests.post(
50
url,
51
header,
52
body
53
)
54
55
print(r.text)
56
57
Advertisement
Answer
There is an example on in the documentation for sending with python You should consider using the Python Client library instead of coding this yourself.
JavaScript
1
18
18
1
def create_message(sender, to, subject, message_text):
2
"""Create a message for an email.
3
4
Args:
5
sender: Email address of the sender.
6
to: Email address of the receiver.
7
subject: The subject of the email message.
8
message_text: The text of the email message.
9
10
Returns:
11
An object containing a base64url encoded email object.
12
"""
13
message = MIMEText(message_text)
14
message['to'] = to
15
message['from'] = sender
16
message['subject'] = subject
17
return {'raw': base64.urlsafe_b64encode(message.as_string())}
18