1

Google の SMTP サービスを使用して、Google アカウントから電子メールを送信したいと考えていました。

そこで、Google API コンソールにアクセスしてサービス アカウントを作成し...@developer.gserviceaccount.com、プライベート証明書をダウンロードしました。

Python では、 oauth2clientライブラリを使用して、このようなペアの資格情報オブジェクトを取得できます: SignedJwtAssertionCredentials. "https://mail.google.com"SMTP サービスのスコープを指定します。

Google のOAuth2 with Python ランスルードキュメントで説明されていますが、その例では、「インストールされたアプリ」があり、Web フローを使用してユーザーに電子メールを送信するための承認を求めることを前提としています。彼らのアカウント。

私の場合、これは自分のアカウントからのものなので、資格情報を承認できるプライベート証明書を備えたサービス アカウントを既にセットアップしています。

この Python スクリプトは、問題を示しています。

import httplib2
import smtplib
import base64
import datetime

from oauth2client.client import SignedJwtAssertionCredentials

http = httplib2.Http()

google_user = "some-account@developer.gserviceaccount.com"
google_cert = open('some-private-cert.p12', 'rb').read()

credentials = SignedJwtAssertionCredentials(
    google_user, google_cert,
    scope='https://mail.google.com/',
)

credentials.refresh(http)

# To demonstrate that we've got a valid access token, let's make a
# couple of assertions:
#
# 1. The credentials have been refreshed:
assert credentials.access_token is not None
#
# 2. The access token hasn't expired (and isn't about to):
assert (credentials.token_expiry - datetime.datetime.utcnow()).total_seconds() > 60

auth_string = 'user=%s\1auth=Bearer %s\1\1' % (
    google_user, credentials.access_token
)

smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
smtp_conn.set_debuglevel(True)
smtp_conn.ehlo()
smtp_conn.starttls()
smtp_conn.ehlo()

# Now, authenticate (but this fails):
smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))

エラー応答は次のとおりです (base64 でデコード):

{"status":"400",
 "schemes":"Bearer",
 "scope":"https://mail.google.com/"}

それが機能するはずだとはわかりませんが、なぜ機能しないのかわかりません。

4

0 に答える 0