Python Gmail API 'not JSON serializable'

标签 python json api email gmail

我想使用 Gmail API 通过 Python 发送电子邮件。一切都应该没问题,但我仍然收到错误消息“发生错误:b'Q29udGVudC1UeXBlOiB0ZXh0L3BsYWluOyBjaGFyc2V0PSJ1cy1hc2NpaSIKTUlNRS ...”这是我的代码:

import base64
import httplib2

from email.mime.text import MIMEText

from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run_flow


# Path to the client_secret.json file downloaded from the Developer Console
CLIENT_SECRET_FILE = 'client_secret.json'

# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'

# Location of the credentials storage file
STORAGE = Storage('gmail.storage')

# Start the OAuth flow to retrieve credentials
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()

# Try to retrieve credentials from storage or run the flow to generate them
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
  credentials = run_flow(flow, STORAGE, http=http)

# Authorize the httplib2.Http object with our credentials
http = credentials.authorize(http)

# Build the Gmail service from discovery
gmail_service = build('gmail', 'v1', http=http)

# create a message to send
message = MIMEText("Message")
message['to'] = "myemail@gmail.com"
message['from'] = "python.api123@gmail.com"
message['subject'] = "Subject"
body = {'raw': base64.b64encode(message.as_bytes())}

# send it
try:
  message = (gmail_service.users().messages().send(userId="me",     body=body).execute())
  print('Message Id: %s' % message['id'])
  print(message)
except Exception as error:
  print('An error occurred: %s' % error)

最佳答案

我有同样的问题,我假设你使用的是 Python3 我在另一篇文章中发现了这个,建议是执行以下操作:

raw = base64.urlsafe_b64encode(message.as_bytes())
raw = raw.decode()
body = {'raw': raw}

查看: https://github.com/google/google-api-python-client/issues/93

关于Python Gmail API 'not JSON serializable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38633781/

相关文章:

Python 记录器不遵守 setLevel?

python - 属性错误: 'NoneType' object has no attribute 'DoCmd'

javascript - 如何使用动态变量访问嵌套的 JSON 数据

c# - 如何使用 C# 获取 X、Y 处像素的颜色?

iOS linkedin 认证

python - 在 2 级列表中形成所有可能的字符串

python - 矢量化新文本数据

arrays - 使用 swift 将 Parse.com json 数组转换为数组

JavaScript 通过选择选项对表数据进行排序

javascript - 获取 API 请求的输出(客户端)