Pythonでメール送信を自動化する方法|SMTP・添付ファイル付きの実用コード例あり

Pythonで業務を自動化したいなら、メール送信の自動化は避けて通れません。
この記事では、Python標準ライブラリである smtplib を使ってメールを自動送信する方法を、添付ファイル付きの実用コードとともに詳しく解説します。

この記事でわかること

  • SMTPを使ったPythonでのメール送信の仕組み
  • Gmailを使った送信設定
  • 添付ファイル付きの送信コード例
  • 実行時の注意点(セキュリティ設定やエラー対応)

前提条件

以下の環境を想定しています

  • Python 3.8以上
  • Gmailアカウント(他のSMTPでも応用可)
  • 安全性確保のため「アプリパスワード」使用

1. Pythonでメールを送信する基本コード

まずはテキストメールを送る基本コードです。

import smtplib
from email.mime.text import MIMEText

# メール情報
sender = 'your_email@gmail.com'
receiver = 'to_email@example.com'
subject = 'テストメール'
body = 'これはPythonから送信されたメールです。'

# メール作成
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver

# SMTPサーバへ接続
smtp_server = 'smtp.gmail.com'
smtp_port = 587
password = 'your_app_password'  # アプリパスワードを使用

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender, password)
    server.send_message(msg)

print("メールを送信しました。")

2. 添付ファイルを送信する方法

次はPDFやExcelなどのファイルを添付するコードです。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os

# メール情報
sender = 'your_email@gmail.com'
receiver = 'to_email@example.com'
subject = '資料を添付しました'
body = '以下にファイルを添付しました。ご確認ください。'
attachment_path = 'document.pdf'  # 添付ファイルのパス

# メール作成
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
msg.attach(MIMEText(body, 'plain', 'utf-8'))

# 添付ファイル追加
with open(attachment_path, 'rb') as f:
    part = MIMEApplication(f.read(), Name=os.path.basename(attachment_path))
    part['Content-Disposition'] = f'attachment; filename="{os.path.basename(attachment_path)}"'
    msg.attach(part)

# SMTPで送信
smtp_server = 'smtp.gmail.com'
smtp_port = 587
password = 'your_app_password'

with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()
    server.login(sender, password)
    server.send_message(msg)

print("添付ファイル付きのメールを送信しました。")

3. Gmailで送信するための設定

Gmailでは、通常のパスワードではログインできないため、「アプリパスワード」を使う必要があります。

手順:

  1. Googleアカウントにログイン
  2. 「セキュリティ」→「2段階認証プロセス」を有効にする
  3. 「アプリ パスワード」を作成
  4. 上記コードの your_app_password にそのパスワードを記入

4. よくあるエラーと対処法

エラー内容対処方法
smtplib.SMTPAuthenticationErrorアプリパスワードを使っているか確認
smtplib.SMTPRecipientsRefused宛先メールアドレスが正しいか確認
Connection timed outファイアウォールやネット環境を確認
STARTTLS not supported by serverポート番号やSMTPサーバ名のミスを確認

5. 応用:複数人に一括送信するには?

宛先をリストで管理し、ループで送るだけです。

receivers = ['a@example.com', 'b@example.com', 'c@example.com']
for receiver in receivers:
    msg['To'] = receiver
    server.send_message(msg)

まとめ

Pythonでのメール自動送信は、smtplibemailライブラリを使えば比較的簡単に実現できます。

業務効率化や自動レポート配信など、さまざまなシーンで活用可能です。
Gmail以外のSMTP(Outlook、SendGridなど)にも応用できますので、ぜひ一度試してみてください。

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