GASのメール送信ができない…それならマニフェスト設定だ(appsscript.json)

Advertisements
Google Apps

Googleフォームで入力されたメールアドレス宛にメールを自動送信するよう設定したく、GAS(Google Apps Script)でGmailApp.sendEmailを使おうとしたら権限がないって蹴られちゃいました。

Exception: スクリプトにはその操作を行う権限がありません。その操作を行うには「(https://www.googleapis.com/auth/gmail.send || https://www.googleapis.com/auth/gmail.compose || https://www.googleapis.com/auth/gmail.modify || https://mail.google.com/ || https://www.googleapis.com/auth/gmail.addons.current.action.compose)」権限が必要です。
at autoNotify(コード:27:12)

気を取り直してMailApp.sendEmailを使っても同じようなエラー。console.logでメールアドレス自体は取れているけれど、メール送信ができていません。

Exception: MailApp.sendEmail を呼び出す権限がありません。必要な権限: https://www.googleapis.com/auth/script.send_mail
at autoNotify(コード:28:11)
https://www.googleapis.com/auth/script.send_mail

You are receiving this error either because your input OAuth2 scope name is invalid or it refers to a newer scope that is outside the domain of this legacy API.

This API was built at a time when the scope name format was not yet standardized. This is no longer the case and all valid scope names (both old and new) are catalogued at https://developers.google.com/identity/protocols/oauth2/scopes. Use that webpage to lookup (manually) the scope name associated with the API you are trying to call and use it to craft your OAuth2 request.

APIが別ドメインなのでOAuth的に良くないよ、ってことなんでしょうか。

兎にも角にもGAS上でマニフェストを設定することにします。

Advertisements

appsscript.jsonにoauthScopesを追加

左サイドメニューのプロジェクトの設定>

【GAS】GmailAppに対するマニフェスト設定>全般設定から「appsscript.json」マニフェスト ファイルをエディタで表示するにチェックを入れます。

エディタに戻るとappscript.jsonが可視化されるようになりました。

ここにoauthScopesを加えて、指摘のあったapiを配列で追加します。

{
  "timeZone": "America/New_York",
  "oauthScopes": [
    "https://www.googleapis.com/auth/script.send_mail",
    "https://www.googleapis.com/auth/gmail.modify"
  ],
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

公式のリファレンスはこちら

Authorization Scopes  |  Apps Script  |  Google for Developers

トリガーを削除・再登録

appsscript.jsonを保存し、トリガーを登録し直します。

削除したら再登録。再登録の際は認証を求められます。しめしめ。

ついでに、GmailAppよりMailAppの方が配信速度が速いらしいのでコードもMailApp.sendEmail()に書き換え。

再度フォームを送信して、ログと、メールが送信できているか確認。

メールOK!ログ、OK!

終わりに。

appsscript.jsonにoauthScopes追加したスコープなのですが、実はどのスコープを追加すればいいのか記載してある箇所がわからなかったため、参考サイトを元に追加しました。詳しい方いたら教えてください。私は上記2つのスコープ追加でメール送信ができました。

参考:

【GAS】GmailAppに対するマニフェスト設定 - Qiita
概要2018/09/01以降、スプレッドシートのGASでGmailApp.sendEmailを使うと以下のエラーが出る。これの対応方法をメモ程度にまとめました。マニフェストの確認…

 

タイトルとURLをコピーしました