2017-04-11 14 views
0

Gmail Apiを使用してPythonでメールを送信していますが、Python 3.4では動作しないようです。Gmail Api for PythonがBad Requestを返す

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のアピ

を消費するために、非UIシステム上で展開するのGmail-api.jsonファイルを使用することができます
関連する問題