この記事について
この記事は、「GmailAPIを使用した最も基本的なメール送信」の内容に基づいて、応用的にファイル送信を行うときに使えるサンプルコードです。
はじめに
GmailAPIの基本的な認証はGmailAPIを使用した最も基本的なメール送信を読んでください。
今回は、token.jsonは、すでに取得済みとして、記事を進めます。
メール送信(ファイル付き)
GmailAPIを使用した最も基本的なメール送信でtoken.jsonの準備が取得できたら、準備完了になります。
今回もプログラムは関数化して、呼び出し処理ができるようにしたいと思います。
モジュールのインポート
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
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_on_file(mail_text, mail_to, title, attachment_path):
scopes = ['https://mail.google.com/']
creds = Credentials.from_authorized_user_file('token.json', scopes)
service = build('gmail', 'v1', credentials=creds)
message = MIMEMultipart()
message['To'] = mail_to
message['From'] ='送信元のメールアドレス'
message['Subject'] = title
body = MIMEText(mail_text)
message.attach(body)
# ファイルの添付
attachment = MIMEBase('application', 'octet-stream')
with open(attachment_path, 'rb') as file:
attachment.set_payload(file.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', f'attachment; filename="{os.path.basename(attachment_path)}"')
message.attach(attachment)
raw = {'raw': message_base64_encode(message)}
service.users().messages().send(userId='me', body=raw).execute()
メール送信用関数の実行
mail_text = "メール本文の内容"
mailaddress = "example@example.com"#送信先のメールアドレス
mail_title = "メールのタイトル"
attachment_path = "フォルダのパス"
mail_post_on_file(mail_text, mailaddress, mail_title, attachment_path)
すべての工程をまとめた、コード
tokenの取得は1箇所でまとまっているのでスキップします。
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import base64
def message_base64_encode(message):
return base64.urlsafe_b64encode(message.as_bytes()).decode()
def mail_post_on_file(mail_text, mail_to, title, attachment_path):
scopes = ['https://mail.google.com/']
creds = Credentials.from_authorized_user_file('token.json', scopes)
service = build('gmail', 'v1', credentials=creds)
message = MIMEMultipart()
message['To'] = mail_to
message['From'] ='送信元のメールアドレス'
message['Subject'] = title
body = MIMEText(mail_text)
message.attach(body)
# ファイルの添付
attachment = MIMEBase('application', 'octet-stream')
with open(attachment_path, 'rb') as file:
attachment.set_payload(file.read())
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', f'attachment; filename="{os.path.basename(attachment_path)}"')
message.attach(attachment)
raw = {'raw': message_base64_encode(message)}
service.users().messages().send(userId='me', body=raw).execute()
mail_text = "メール本文の内容"
mailaddress = "example@example.com"#送信先のメールアドレス
mail_title = "メールのタイトル"
attachment_path = "フォルダのパス"
mail_post_on_file(mail_text, mailaddress, mail_title, attachment_path)
最後に
今後は、HTMLのメール配信もできるようになりたいと思います。