【发布时间】:2020-04-15 03:57:31
【问题描述】:
我认为 Gmail API 和 Python3 存在问题。 文档中的原始代码在 Python2 中,但出于多种原因,包括我的应用程序已经在使用 Python3,我将代码传递给了 python3。
所以...在对几个问题进行排序后,包括 400 请求错误,(显然我提供给 google 的身份验证没有正确完成)我正面临(我希望)最后一个问题,显然我'我试图读取一个文件,但是
即使只是做token.read() 也会产生同样的问题。
一旦您授权 google 访问您的电子邮件帐户并且该应用可以自动发送电子邮件,就会自动生成 token.pickle 文件。
我知道 credentials.json 文件是正确的,因为这是告诉谷歌你是谁的关键,它总是正确读取我的凭据,重定向我以授权我的应用程序。
这是发送电子邮件的应用程序,我认为它非常简单,我按照文档查看了other issues like this one,终于走到了这一步:
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError
# from httplib2 import Http
# from oauth2client import client, tools, file
import base64
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
from apiclient import errors
SCOPES = 'https://mail.google.com/'
def SendMessage(service, user_id, message):
"""Send an email message.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
message: Message to be sent.
Returns:
Sent Message.
"""
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print(f'Message Id: {message["id"]}')
return message
except errors.HttpError as error:
print(f'An error occurred: {error}')
def CreateMessage(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
message_bytes = message.as_string().encode('utf-8')
# return { 'raw': base64.urlsafe_b64encode(message.as_string()) }
# return { 'raw': base64.urlsafe_b64encode(message_bytes) }
raw = base64.urlsafe_b64encode(message_bytes)
return raw.decode()
def main():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'r') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('gmail', 'v1', credentials=creds)
# Create
message = CreateMessage('my-email@gmail.com', 'destination@gmail.com', 'Testing Gmail API', 'Hi GMAIL API')
# Send
SendMessage(service, "me", message)
if __name__ == '__main__':
main()
如果有人已经解决了这个问题以及如何解决,我真的不知道该怎么做。
谢谢!
【问题讨论】:
-
您用
'wb'编写泡菜,但只用'r'将其读回——问题就这么简单吗?如果不是,请添加确切的错误消息并指出发生的行。
标签: python-3.x email gmail gmail-api