0
我使用Gmail Api在python中发送电子邮件,但它看起来不适用于Python 3.4。用于Python的Gmail Api返回错误的请求
下面是代码:
msg = MIMEText(html, 'html')
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
username = '[email protected]'
CLIENT_SECRET_FILE = '/client_secret.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(CLIENT_SECRET_FILE, SCOPES)
try:
http_auth = credentials.authorize(Http())
service = discovery.build('gmail', 'v1', http=http_auth)
gmailMsg = {'raw': base64.urlsafe_b64encode(msg.as_string().encode('utf-8')).decode('utf-8')}
message = (service.users().messages().send(userId = username, body = gmailMsg).execute())
错误:
<HttpError 400 when requesting https://www.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Bad Request">
为了记录在案,我为我的项目创建的凭据是对于非UI平台(服务器对服务器)服务帐户。 我想可能是gmailMsg对象编码不正确。但是,当我在Google Apis Explorer中使用它时,请猜测它的工作原理。 我可以看到的唯一区别是在Python中,JSON在Google API资源管理器中使用单引号,它促使我使用双引号。
任何人有任何建议吗?
P/S:我已经试过以下编码选项:
base64.urlsafe_b64encode(msg.as_string().encode('utf-8')).decode('utf-8')
base64.urlsafe_b64encode(msg.as_string().encode('utf-8')).decode('ascii')
base64.urlsafe_b64encode(msg.as_string().encode('ascii')).decode('ascii')
base64.urlsafe_b64encode(msg.as_bytes()).decode('utf-8')
base64.urlsafe_b64encode(msg.as_bytes()).decode('ascii')
base64.urlsafe_b64encode(msg.as_bytes()).decode()
编辑:有趣的是,我试图用标签的API,它不要求身体。但我得到了同样的错误。唯一的变化是:
SCOPES = ['https://www.googleapis.com/auth/gmail.labels']
message = (service.users().labels().list(userId = username).execute())