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