2017-04-11 41 views
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()) 

回答

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阿比

相关问题