Gmail Api for Python返回错误请求

时间:2017-04-11 16:43:35

标签: python python-3.x gmail-api http-error bad-request

我使用Gmail Api在python中发送电子邮件,但看起来它不能与Python 3.4一起使用。

以下是代码:

msg = MIMEText(html, 'html')
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
username = 'user@gmail.com'
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 Explorer中,它让我使用双引号。

有人有任何建议吗?

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())

1 个答案:

答案 0 :(得分:0)

事实证明,要使用Gmail API,我必须使用OAuth凭据而不是服务帐户。要在非UI系统中使用Gmail API,您可以启动身份验证,然后复制oauth api保存的凭据。以下是代码:

home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
                               'gmail-api.json')

store = Storage(credential_path)
credentials = store.get()
f not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    if flags:
        credentials = tools.run_flow(flow, store, flags)
    else: # Needed only for compatibility with Python 2.6
        credentials = tools.run(flow, store)

然后您可以使用gmail-api.json文件在非UI系统上部署以使用Gmail Api