google colaboratoryでgmail APIを使いたく、以下のように実行したのですが、認証の途中でエラーとなり、どのようにしたらよいか教えていただけますでしょうか。
1.google cloud platformでoauth2.0クライアントIDを作成し(デスクトップクライアント)、jsonファイルをcolaboratoryにマウントしたgoogleドライブ上に保存。
2.以下のサイトのStep1、2のコードサンプルをほぼ丸写ししてpythonのコードを実行
https://developers.google.com/gmail/api/quickstart/python?hl=ja
3.認証のため以下の操作をしました。
・「Please visit this URL to authorize this application:https://・・・」と認証画面のリンクが表示、
・リンク先で「アカウントの選択」、
・「このアプリは Google で確認されていません 現在テスト中のアプリへのアクセスが許可されました。招待元のデベロッパーを信頼できる場合のみ、続行してください。」画面でcontinue、
・「~が Google アカウントへのアクセスを求めています」画面で「アクセスできる情報」を選択
4.エラー
「このサイトにアクセスできませんlocalhost で接続が拒否されました。・・・ERR_CONNECTION_REFUSED」
なるべく要約しようと思いましたが、長文となり申し訳ございません。よろしくお願いいたします。
コメントありがとうございます。以下のようなコードです。
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
from __future__ import print_function
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from email.mime.text import MIMEText
import base64
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode}
def send_message(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
print( 'Message Id: %s' % message['id'])
return message
except errors.HttpError as e:
print( 'An error occurred: %s' % error)
def main():
"""Shows basic usage of the Gmail API.
Lists the user's Gmail labels.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'/content/drive/MyDrive/*****/******.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('gmail', 'v1', credentials=creds)
sender = 'hayamaya18@gmail.com'
to = 'rabewato@mbox.re'
subject = 'テストメール'
message_text = 'これはGmail APIによるテストメールです。'
message = create_message(sender, to, subject, message_text)
send_message(service,'me',message)
main()