2017-04-11 38 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阿比

相關問題