質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Google Cloud Platform

Google Cloud Platformは、Google社がクラウド上で提供しているサービス郡の総称です。エンドユーザー向けサービスと同様のインフラストラクチャーで運営されており、Webサイト開発から複雑なアプリ開発まで対応可能です。

Gmail

GmailとはGoogleによって提供されているウェブメールのサービスのことです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

Q&A

解決済

1回答

849閲覧

Python Gmailの自動送信がローカルでは実行できるのに本番環境でエラーになる

kanafuku

総合スコア12

Google Cloud Platform

Google Cloud Platformは、Google社がクラウド上で提供しているサービス郡の総称です。エンドユーザー向けサービスと同様のインフラストラクチャーで運営されており、Webサイト開発から複雑なアプリ開発まで対応可能です。

Gmail

GmailとはGoogleによって提供されているウェブメールのサービスのことです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

API

APIはApplication Programming Interfaceの略です。APIはプログラムにリクエストされるサービスがどのように動作するかを、デベロッパーが定めたものです。

0グッド

0クリップ

投稿2022/06/10 11:05

前提

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 のアドレスではありません。
そちらが関係しているのでしょうか、、、

とにかくローカルでは問題なくメールが送れます。
詳しい方がいらっしゃいましたらご教授お願いいたします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

自己解決しました!!
メールを送信したいGoogleアカウントのログイン情報とその設定が必要でした。

Python

1 2def send_email(conveni_user_email_address): 3 4 load_dotenv() 5 gmail_account = "support@miroamurette.com" 6 gmail_password = os.environ['GOOGLE_PASSWORD'] 7 8 subject = "Gmail 自動送信" 9 body = ''' 10 ※このメールはシステムからの自動送信です。 11 ''' 12 13 msg = MIMEText(body, "plain") 14 msg["Subject"] = subject 15 msg["To"] = conveni_user_email_address 16 msg["From"] = gmail_account 17 18 server = smtplib.SMTP_SSL("smtp.gmail.com", 465, context=ssl.create_default_context()) 19 server.login(gmail_account, gmail_password) 20 print("ログインOK") 21 server.send_message(msg) 22 print("メール送信完了") 23

投稿2022/06/23 05:54

kanafuku

総合スコア12

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問