Day 43:メール処理で「自動通知できるPython」を手に入れる
Day 43では、業務自動化で欠かせない メール処理 を学びます。 CSV集計・PDF生成・レポート作成など、これまで作ってきたツールを 自動通知メール と組み合わせることで、 「処理が終わったら自動でメールが飛ぶ」 「毎朝レポートをメールで送る」 といった“本当に使える自動化”が完成します。
扱う内容は次の4つです。
- メール送信の基本
- 添付ファイル
- HTMLメール
- 自動通知の考え方
初心者向けにかみ砕いて、ステップバイステップで解説します。
メール送信の仕組みをイメージする
メール送信は、Pythonから SMTP(メール送信プロトコル) を使って行います。 Python標準ライブラリの smtplib と email を使えば、追加インストールなしでメール送信ができます。
メール送信の流れは次の通りです。
- SMTPサーバーに接続する
- メールの内容(件名・本文・宛先)を作る
- サーバーに送信する
- 接続を閉じる
この流れをコードに落とし込んでいきます。
メール送信の基本(テキストメール)
まずは最も基本的な「テキストメール」を送る例です。
# day43_mail_basic.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_text_mail():
"""テキストメールを送信する基本例です。"""
# 送信元・送信先
from_addr = "your_email@example.com"
to_addr = "target@example.com"
# メールの入れ物(MIMEMultipart)
msg = MIMEMultipart()
msg["Subject"] = "Pythonからのテストメール"
msg["From"] = from_addr
msg["To"] = to_addr
# 本文(テキスト)
body = "これはPythonから送信したテストメールです。"
msg.attach(MIMEText(body, "plain"))
# SMTPサーバーに接続して送信
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls() # TLSで暗号化
server.login("your_email@example.com", "your_password")
server.send_message(msg)
print("メールを送信しました。")
if __name__ == "__main__":
send_text_mail()
Python重要ポイント
MIMEMultipart()は「メールの入れ物」。MIMEText(body, "plain")でテキスト本文を作る。server.starttls()で通信を暗号化する。server.login()でメールアカウントにログインする。
添付ファイル付きメールを送る
CSVやPDFを自動生成したら、メールに添付して送ることが多いです。
# day43_mail_attachment.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def send_mail_with_attachment():
"""添付ファイル付きメールを送信する例です。"""
from_addr = "your_email@example.com"
to_addr = "target@example.com"
msg = MIMEMultipart()
msg["Subject"] = "レポート送付(Python自動化)"
msg["From"] = from_addr
msg["To"] = to_addr
# 本文
body = "自動生成したレポートを添付します。"
msg.attach(MIMEText(body, "plain"))
# 添付ファイル(例:report.pdf)
filename = "report.pdf"
with open(filename, "rb") as f:
attachment = MIMEApplication(f.read(), _subtype="pdf")
attachment.add_header("Content-Disposition", "attachment", filename=filename)
msg.attach(attachment)
# SMTP送信
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login("your_email@example.com", "your_password")
server.send_message(msg)
print("添付ファイル付きメールを送信しました。")
if __name__ == "__main__":
send_mail_with_attachment()
Python重要ポイント
MIMEApplicationを使うと、PDF・CSV・Excelなど何でも添付できる。Content-Dispositionのattachmentが「添付ファイル」として扱われる鍵。
HTMLメールを送る(見栄えの良い通知メール)
HTMLメールを使うと、太字・色・表などを使った見やすいメールが作れます。
# day43_mail_html.py
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_html_mail():
"""HTMLメールを送信する例です。"""
from_addr = "your_email@example.com"
to_addr = "target@example.com"
msg = MIMEMultipart("alternative")
msg["Subject"] = "HTMLメールのサンプル"
msg["From"] = from_addr
msg["To"] = to_addr
# HTML本文
html = """
<html>
<body>
<h2 style="color: blue;">Python自動化レポート</h2>
<p>本日の処理が完了しました。</p>
<p><b>売上集計:</b> 120,000円</p>
<p>詳細は添付ファイルをご確認ください。</p>
</body>
</html>
"""
msg.attach(MIMEText(html, "html"))
# SMTP送信
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login("your_email@example.com", "your_password")
server.send_message(msg)
print("HTMLメールを送信しました。")
if __name__ == "__main__":
send_html_mail()
Python重要ポイント
MIMEMultipart("alternative")は「テキストとHTMLを両方入れられる」形式。MIMEText(html, "html")でHTMLメールを作る。- HTMLメールは通知メールの見栄えを大きく改善できる。
自動通知の考え方
1. 「通知したいイベント」を明確にする
例:
- CSV集計が完了したら通知
- PDFレポートを生成したら通知
- エラーが起きたら通知
- 毎朝9時にレポートを送信
2. 通知処理を関数にまとめる
def notify(message):
"""通知メールを送る関数(簡易版)"""
# ここに send_text_mail() や send_html_mail() を呼ぶ処理を書く
print("通知:", message)
Python3. バッチ処理の最後に通知を入れる
def run_batch():
try:
print("処理開始")
# CSV集計などの処理
print("処理完了")
notify("バッチ処理が正常に完了しました。")
except Exception as e:
notify(f"エラーが発生しました: {e}")
Python4. 定期実行(Day 42)と組み合わせる
Day 42で作ったスケジューラと組み合わせると、
- 毎日9時にバッチ処理
- 終わったら自動でメール通知
という「本当に使える自動化」が完成します。
Day 43総合テンプレート:メール処理ツール
# day43_mail_tool.py
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_mail(subject, body, to_addr, attachment_path=None, html=False):
"""メール送信の汎用関数です。"""
from_addr = "your_email@example.com"
msg = MIMEMultipart()
msg["Subject"] = subject
msg["From"] = from_addr
msg["To"] = to_addr
# 本文(HTML or テキスト)
if html:
msg.attach(MIMEText(body, "html"))
else:
msg.attach(MIMEText(body, "plain"))
# 添付ファイル
if attachment_path:
with open(attachment_path, "rb") as f:
attachment = MIMEApplication(f.read())
attachment.add_header("Content-Disposition", "attachment", filename=attachment_path)
msg.attach(attachment)
# SMTP送信
with smtplib.SMTP("smtp.example.com", 587) as server:
server.starttls()
server.login("your_email@example.com", "your_password")
server.send_message(msg)
print("メールを送信しました。")
def main():
# テキストメール
send_mail(
subject="テスト通知",
body="Pythonからのテキスト通知メールです。",
to_addr="target@example.com"
)
# HTMLメール
send_mail(
subject="HTML通知",
body="<h2>Python自動化レポート</h2><p>処理が完了しました。</p>",
to_addr="target@example.com",
html=True
)
# 添付ファイル付きメール
send_mail(
subject="レポート送付",
body="自動生成したレポートを添付します。",
to_addr="target@example.com",
attachment_path="report.pdf"
)
if __name__ == "__main__":
main()
PythonDay 43のまとめ
Day 43では、メール処理として、
smtplibとemailを使ったメール送信の基本MIMEApplicationを使った添付ファイル付きメールMIMEText(..., "html")を使ったHTMLメール- バッチ処理と組み合わせた「自動通知」の考え方
をステップバイステップで体験していただきました。
ここまで来ると、 「処理が終わったら自動でメールが飛ぶ」 「毎朝レポートをメールで送る」 といった、実務で本当に役立つ自動化が作れるようになります。
