Pythonによるメール送信のさまざまな実装方法

SMTPライブラリを用いた基本的なメール送信

Pythonでは、標準ライブラリのsmtplibemail.mimeモジュールを使用して、低レベルながら柔軟なメール送信が可能です。以下は、TLS暗号化を用いてGmailなどの外部SMTPサーバーに接続する例です。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_basic_mail(sender: str, receiver: str, subject: str, body: str, smtp_host: str, port: int, login: str, app_password: str):
    message = MIMEMultipart()
    message["From"] = sender
    message["To"] = receiver
    message["Subject"] = subject
    message.attach(MIMEText(body, "plain", "utf-8"))

    try:
        server = smtplib.SMTP(smtp_host, port)
        server.starttls()
        server.login(login, app_password)
        server.send_message(message)
        print("送信完了: メールが正常に送られました")
    except smtplib.SMTPException as e:
        print(f"送信失敗: {e}")
    finally:
        server.quit()

# 使用例(Gmail)
send_basic_mail(
    sender="sender@gmail.com",
    receiver="recipient@example.com",
    subject="自動通知",
    body="これはPythonから送信されたテストメッセージです。",
    smtp_host="smtp.gmail.com",
    port=587,
    login="sender@gmail.com",
    app_password="your_app_password"
)

yagmailによる簡易送信

yagmailはOAuthやアプリパスワードに対応したサードパーティ製パッケージで、認証処理が簡素化されています。インストールはpip install yagmailで行えます。

import yagmail

def quick_send():
    yag = yagmail.SMTP("your_email@gmail.com", oauth2_file="path/to/oauth2_creds.json")
    contents = [
        "本文メッセージ",
        "追加のテキスト情報",
        "attachment.png"  # 添付ファイルも可能
    ]
    yag.send(
        to="target@example.com",
        subject="簡易送信テスト",
        contents=contents
    )
    print("yagmailで送信成功")

quick_send()

Flask-MailによるWebアプリ統合

Flaskアプリ内でメール機能を提供する場合、Flask-Mail拡張を使うと設定と送信が一元管理できます。非同期送信も別スレッドで実装可能です。

from flask import Flask
from flask_mail import Mail, Message
import threading

app = Flask(__name__)
app.config.update(
    MAIL_SERVER="smtp.gmail.com",
    MAIL_PORT=587,
    MAIL_USE_TLS=True,
    MAIL_USERNAME="service@yourapp.com",
    MAIL_PASSWORD="app_password",
    MAIL_DEFAULT_SENDER="service@yourapp.com"
)

mail = Mail(app)

def send_async_email(application, msg):
    with application.app_context():
        mail.send(msg)

@app.route("/notify")
def trigger_notification():
    msg = Message("アラート通知", recipients=["user@domain.com"])
    msg.body = "システムから重要な通知があります。"
    thread = threading.Thread(target=send_async_email, args=(app, msg))
    thread.start()
    return "通知リクエストを送信しました"

if __name__ == "__main__":
    app.run(debug=True)

環境変数とセキュリティの考慮

実際の運用では、認証情報はソースコード内に直接記述せず、環境変数または設定ファイルで管理すべきです。

import os
from dotenv import load_dotenv

load_dotenv()  # .envファイルから読み込み

SMTP_USER = os.getenv("SMTP_USER")
SMTP_PASS = os.getenv("SMTP_APP_PASSWORD")

特にGmailを利用する場合は、通常のパスワードではなく「アプリパスワード」の使用が推奨されます。

タグ: smtplib yagmail Flask-Mail Pythonメール送信 SMTP認証

7月5日 23:39 投稿