0
2

Pythonを使用したメール送信スクリプトの作成

Posted at

はじめに

この記事では、Pythonを使用してメールを送信するスクリプトの作成方法を紹介します。このスクリプトは、JSONファイルから設定を読み込み、SMTPサーバーを介してメールを送信し、必要に応じてファイルを添付する機能を持っています。

サンプルコードはGitHubリポジトリで確認できます: python-mail-sender

使用するライブラリ

このスクリプトでは以下のライブラリを使用しています。これらは標準ライブラリに含まれているため、追加のインストールは不要です。

  • json: JSONファイルから設定を読み込むために使用します。
  • smtplib: SMTPサーバーを介してメールを送信するために使用します。
  • email.mime: メールの作成に必要な各種MIMEタイプを扱います。
  • os: ファイルパスの操作やファイル名の抽出に使用します。

スクリプトの概要

このスクリプトは以下の3つの主要な部分で構成されています。

  1. 設定の読み込み: メールアドレスやSMTPサーバーの設定、メールの件名や本文をテンプレートから読み込みます。
  2. メールの作成と送信: 設定に基づいてメールを作成し、SMTPサーバーを介して送信します。
  3. ファイルの添付: 必要に応じてファイルをメールに添付します。

設定の読み込み

まず、メールアドレスや件名、本文のテンプレートをJSONファイルやテキストファイルから読み込みます。

def load_email_settings():
    with open('mail/mail_address.json', 'r', encoding='utf-8') as f:
        email_settings = json.load(f)["email_settings"]
    with open('mail/mail_subject.txt', 'r', encoding='utf-8') as f:
        mail_subject = f.read().strip()
    with open('mail/mail_body.txt', 'r', encoding='utf-8') as f:
        body_template = f.read().strip()
    return email_settings, mail_subject, body_template

SMTPサーバーの設定の読み込み

次に、SMTPサーバーの設定をJSONファイルから読み込みます。

with open('settings/smtp.json', 'r', encoding='utf-8') as f:
    smtp_settings = json.load(f)

メールの作成と送信

以下のコードは、メールを作成し、SMTPサーバーを介して送信する部分です。

def send_email_with_attachment(email_settings, subject, body_template, result_data, attachment_path):
    msg = MIMEMultipart()
    msg['From'] = f"{email_settings['FromName']} <{email_settings['From']}>"
    msg['To'] = ", ".join(email_settings['TO'])
    msg['Cc'] = ", ".join(email_settings['CC'])
    msg['Subject'] = subject
    msg['Date'] = formatdate(localtime=True)

    body_filled = body_template.format(
        total_count=result_data['totalCount'],
        succeed_count=result_data['succeededCount'],
        added_count=result_data['addedCount'],
        error_count=result_data['failedCount']
    )
    msg.attach(MIMEText(body_filled, 'plain', 'utf-8'))

    with open(attachment_path, "rb") as attachment:
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(attachment.read())
        encoders.encode_base64(part)
        filename = os.path.basename(attachment_path)
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)

    with smtplib.SMTP(smtp_settings['smtp_host'], smtp_settings['smtp_port']) as server:
        smtp_user = smtp_settings.get('smtp_user')
        smtp_password = smtp_settings.get('smtp_password')
        if smtp_user and smtp_password:
            server.login(smtp_user, smtp_password)
        server.send_message(msg)

ここでは、MIMEMultipartオブジェクトを使用してメールを作成し、本文を設定し、ファイルを添付しています。その後、smtplib.SMTPを使用してSMTPサーバーに接続し、メールを送信します。

まとめ

このスクリプトを使用することで、簡単にメールを自動化して送信できるようになります。設定ファイルを適切に準備することで、様々なメールを動的に作成し、送信することが可能です。

0
2
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
0
2