2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

GmailAPIを使用した最も基本的なメール送信

Last updated at Posted at 2023-05-08

この記事について

この記事は、GmailAPIを用いた最も一般的なメール送信について、忘れたとき用のために、私的に残しておくものになります。

Client-Secretファイルのダウンロード

Google API Consoleにログインして、プロジェクトを選択します。
GmailAPIを有効にします。
左側のメニューで、「認証情報」をクリックします。
「認証情報を作成」をクリックし、「OAuth クライアントID」を選択します。
必要に応じて、アプリケーションの種類を選択して、必要な情報を入力します。
「作成」をクリックすると、JSONファイルがダウンロードされます。
JSONファイルをプロジェクトの適切なディレクトリに保存します。

Tokenの取得について

前章で取得したクライアントファイルを準備してください。
(サンプルコードの中では、"client_secret.json"を使用しています)
まずは、token.jsonを取得します。
token.jsonは、Gmail APIを使用するためにOAuth 2.0認証フローを通過した後に、アクセストークンやリフレッシュトークンを保存するためのファイルです。

from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://mail.google.com/']

flow = InstalledAppFlow.from_client_secrets_file(
   './client_secret.json', SCOPES)
creds = flow.run_local_server(port=0)

with open('token.json', 'w') as token:
   token.write(creds.to_json())

このコードを実行すると、ブラウザのOAuth認証画面が立ち上がり、対象のグーグルアカウントを選択して、認証をしてください。

メール送信

上の章すべが終了したら、ようやく準備完了になります。
正しく処理ができているのなら、対象ディレクトリに"token.json"が生成されていると思います。
今回のプログラムは関数化して、呼び出し処理ができるようにしたいと思います。

モジュールのインポート

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from email.mime.text import MIMEText
import base64

文字列をbase64に変換する関数

def message_base64_encode(message):
    return base64.urlsafe_b64encode(message.as_bytes()).decode()

メール送信用関数の作成

送信元のメールアドレスの部分は書き換えてください。

def mail_post(mail_text, mail_to, title):
    scopes = ['https://mail.google.com/']
    creds = Credentials.from_authorized_user_file('token.json', scopes)
    service = build('gmail', 'v1', credentials=creds)

    message = MIMEText(f'{mail_text}')
    message['To'] = f'{mail_to}'
    message['From'] = '送信元のメールアドレス'
    message['Subject'] = f'{title}'

    raw = {'raw': message_base64_encode(message)}
    service.users().messages().send(
        userId='me',
        body=raw
    ).execute()

メール送信用関数の実行

mail_text = "メール本文の内容"
mailaddress = "example@example.com"#送信先のメールアドレス
mail_title = "メールのタイトル"
mail_post(mail_text, mailaddress, mail_title)

すべての工程をまとめた、コード

tokenの取得は1箇所でまとまっているのでスキップします。

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from email.mime.text import MIMEText
import base64

def mail_post(mail_text, mail_to, title):
    scopes = ['https://mail.google.com/']
    creds = Credentials.from_authorized_user_file('token.json', scopes)
    service = build('gmail', 'v1', credentials=creds)

    message = MIMEText(f'{mail_text}')
    message['To'] = f'{mail_to}'
    message['From'] = '送信元のメールアドレス'
    message['Subject'] = f'{title}'

    raw = {'raw': message_base64_encode(message)}
    service.users().messages().send(
        userId='me',
        body=raw
    ).execute()

mail_text = "メール本文の内容"
mailaddress = "example@example.com"#送信先のメールアドレス
mail_title = "メールのタイトル"
mail_post(mail_text, mailaddress, mail_title)

最後に

ファイルの送信や、HTML形式のメール送信などもできるので、参考にしてみてください

参考

Gmail API の概要

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?