yagmail を使ったメール送信(例:126ウェブメール)
yagmail は、SMTP サーバーを通じて Python から簡易的にメールを送信するためのライブラリです。
インストール手順
pip install yagmail keyring schedule imbox
# または国内ミラーサイトを使用
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ yagmail keyring schedule imbox
基本的なメール送信
import yagmail
# SMTP サーバー接続(アカウント情報)
smtp = yagmail.SMTP(user="sender@126.com", password="app_password", host="smtp.126.com")
# 本文(文字列のリストまたは1つの文字列で可)
body = [
"これは第一行の内容です。",
"こちらは第二行の内容です。"
]
# メール送信
smtp.send(
to="recipient@example.com",
subject="テストメール",
contents=body
)
# 接続を閉じる
smtp.close()
複数受信者への一括送信
# 受信者をリストで指定
recipients = ["user1@126.com", "user2@qq.com", "user3@gmail.com"]
smtp.send(
to=recipients,
subject="グループ送信テスト",
contents=body
)
安全な認証:keyring を使ったパスワード管理
コード内にパスワードを平文で記述しないよう、システムキーチェーンに登録する方法が推奨されます。
# 初回登録(一度だけ実行)
import keyring
keyring.set_password("yagmail_service", "sender@126.com", "your_app_password")
# その後の利用
import yagmail
smtp = yagmail.SMTP(user="sender@126.com") # password 引数不要
smtp.send(to=" recipient@example.com", subject="Keyring利用テスト", contents=["安全に送信中"])
schedule を使った定期実行
轻量なスケジューラー library で、簡易的なタスクの周期実行が可能です。
import schedule
import time
def send_report():
print("レポート送信タスクを実行中...")
# 実際には yagmail を使ったメール送信処理をここに記述
# タスクスケジュール設定
schedule.every(10).minutes.do(send_report) # 10分ごと
schedule.every().hour.do(send_report) # 毎時
schedule.every().day.at("09:30").do(send_report) # 毎日9:30
schedule.every(5).to(10).days.do(send_report) # 5~10日おき(ランダム)
schedule.every().monday.do(send_report) # 毎週月曜
schedule.every().wednesday.at("13:15").do(send_report) # 毎週水曜13:15
# 無限ループでスケジュール実行
while True:
schedule.run_pending()
time.sleep(1)
参数付き関数のスケジューリング
def notify_user(user_name, message):
print(f"{user_name} へ送信:{message}")
schedule.every(5).minutes.do(notify_user, user_name="田中", message="お知らせ")
# 必ず `.do()` の引数として渡す順序は関数定義と一致させる
schedule.every().hour.do(notify_user, "佐藤", "定期ニュース")
imbox を使ったメール受信処理(参考)
受信メールの取得や Nichtungs処理は imbox ライブラリで実現可能です(例:未読メールチェック)。
from imbox import Imbox
import ssl
context = ssl.create_default_context()
with Imbox("imap.126.com", username="sender@126.com", password="app_password", ssl=True, ssl_context=context) as imap:
# 未読メッセージを取得
unread_messages = imap.messages(unread=True)
for uid, msg in unread_messages:
print(f"件名: {msg.subject}")
print(f"本文: {msg.body}")
# 読み済みにマーク
imap.mark_seen(uid)