是否可以使用 Python 请求库仅使用 Google Gmail API 发送 Gmail

Is it possible to use the Python requests library to send Gmail only using the Google Gmail API

是否可以使用 Python 请求库仅使用 Google Gmail API 发送 Gmail?我正在尝试使用 python 请求库发送 Gmail。但它以错误 401 结束。我想知道用 Google Gmail API.

发送 Gmail 的正确方法是什么
import sys
import requests
import base64
import sys
from email.mime.text import MIMEText

AccessToken = ""

params = {
        "grant_type":    "refresh_token",
        "client_id":     "xxxxxxxxxxxxxxx",
        "client_secret": "xxxxxxxxxxxxxxx",
        "refresh_token": "xxxxxxxxxxxxxxxxxxxx",
        }

authorization_url = "https://www.googleapis.com/oauth2/v4/token"

r = requests.post(authorization_url, data=params)

if r.ok:
    AccessToken = str((r.json()['access_token']))

EmailFrom = "Test1@gmail.com"
EmailTo = "test2@gmail.com"

def create_message(sender, to, subject, message_text):
   
    message = MIMEText(message_text, 'html')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    body = {'raw': raw}
    return body


body  = create_message(EmailFrom, EmailTo, "Just wanna Say Waka Waka!", "Waka Waka!")


url = "https://gmail.googleapis.com/gmail/v1/users/me/messages/send"

header = {
    'Authorization': 'Bearer ' + AccessToken,
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}

r = requests.post(
    url,
    header,
    body
)

print(r.text)

  1. 确保您使用的哈希算法与 Gmail API 所期望的相同。 应该可以看到他们希望您发送的确切令牌。并尝试将您的哈希算法用于您尝试发送的令牌。例如,我总是尝试使用终端转义我的代码,并尝试在之前使用单独的代码块,以了解它在您使用的 cmd/linux 终端中的空白 python shell 中根据需要工作.
  2. 在您的 Gmail API 选项卡上确保您启用了所有必要的范围。可能主要问题正是与范围有关。在使用 Google 地图 API
  3. 时遇到了非常相似的情况

此外,您能否向我们提供更多信息,您对auth_url的第一个请求也失败了,或者仅对第二个请求不起作用?

sending with python 的文档中有一个示例,您应该考虑使用 Python 客户端库,而不是自己编写代码。

def create_message(sender, to, subject, message_text):
  """Create a message for an email.

  Args:
    sender: Email address of the sender.
    to: Email address of the receiver.
    subject: The subject of the email message.
    message_text: The text of the email message.

  Returns:
    An object containing a base64url encoded email object.
  """
  message = MIMEText(message_text)
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.urlsafe_b64encode(message.as_string())}