前提
Gmail APIでGmailの自動送信の処理をローカルでは実行できるのに
本番環境だとエラーになってしまう
実現したいこと
Gamilの送信を自動化したい
発生している問題・エラーメッセージ
Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=811734202173-pmptrbq7dandqhd65eqsbg0lo0b59a3k.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A23480%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.send&state=hERSs7CRTyB2ioK6asmuokFSwgjmGy&access_type=offline
上記のリンクを叩くと、
**
承認エラー
エラー 400: invalid_request
Missing required parameter: scope
**
このようなメッセージが出てきます。
該当のソースコード
Python
1from __future__ import print_function 2import pickle 3import os.path 4from googleapiclient.discovery import build 5from google.auth.transport.requests import Request 6from google_auth_oauthlib.flow import InstalledAppFlow 7from email.mime.text import MIMEText 8import base64 9from apiclient import errors 10import base64 11from email.message import EmailMessage 12import google.auth 13from googleapiclient.errors import HttpError 14 15 16# If modifying these scopes, delete the file token.pickle. 17SCOPES = ['https://www.googleapis.com/auth/gmail.send'] # メール送信を使う時のスコープ 18 19def create_message(sender, to, subject, message_text): 20 """Create a message for an email. 21 22 Args: 23 sender: Email address of the sender. 24 to: Email address of the receiver. 25 subject: The subject of the email message. 26 message_text: The text of the email message. 27 28 Returns: 29 An object containing a base64url encoded email object. 30 """ 31 message = MIMEText(message_text) 32 message['to'] = to 33 message['from'] = sender 34 message['subject'] = subject 35 36 return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} 37 38 39def send_message(service, user_id, message): 40 """Send an email message. 41 42 Args: 43 service: Authorized Gmail API service instance. 44 user_id: User's email address. The special value "me" 45 can be used to indicate the authenticated user. 46 message: Message to be sent. 47 48 Returns: 49 Sent Message. 50 """ 51 try: 52 message = (service.users().messages().send(userId=user_id, body=message) 53 .execute()) 54 print('Message Id: %s' % message['id']) 55 return message 56 except errors.HttpError as error: 57 print('An error occurred: %s' % error) 58 59 60def main(): #data, context 61 creds = None 62 # The file token.pickle stores the user's access and refresh tokens, and is 63 # created automatically when the authorization flow completes for the first 64 # time. 65 if os.path.exists('token.pickle'): 66 with open('token.pickle', 'rb') as token: 67 creds = pickle.load(token) 68 # If there are no (valid) credentials available, let the user log in. 69 if not creds or not creds.valid: 70 if creds and creds.expired and creds.refresh_token: 71 creds.refresh(Request()) 72 else: 73 flow = InstalledAppFlow.from_client_secrets_file( 74 'credentials.json', SCOPES) 75 creds = flow.run_local_server(port=0) 76 77 service = build('gmail', 'v1', credentials=creds) 78 79 # Call the Gmail API 80 sender = '0000@gmail.com' 81 to = '0000@gmail.com' 82 subject = 'pythonで自動設定' 83 message_text = 'メール送信テスト' 84 mail = create_message(sender, to, subject, message_text) 85 send_message(service, 'me', mail) 86 print("メール送信できた!") 87 88 89if __name__ == '__main__': 90 main() 91
試したこと
- リストgoogleアカウントの設定で安全性の低いアプリケーションを許可にしてみましたダメでした
- リストGCPのプロジェクトやサービスアカウントも作成し直して再デプロイしましたがダメでした
Gmail APIは有効になっており、OAuth 同意画面も設定済みです。
補足情報(FW/ツールのバージョンなど)
該当のソースコード内のsenderに当たるアカウントが
会社の独自ドメインなので gmail.com のアドレスではありません。
そちらが関係しているのでしょうか、、、
とにかくローカルでは問題なくメールが送れます。
詳しい方がいらっしゃいましたらご教授お願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。