【Python】メールに自動返信するスクリプト|IMAPとSMTPの基本実装

Python

問い合わせ対応や受付確認など、メールへの自動返信は業務効率化において非常に有効です。Pythonでは、IMAPでメールの受信を監視し、SMTPで返信を送ることができます。

この記事では、Pythonでメールを自動取得・返信する基本的なスクリプトの実装方法を紹介します。

事前準備

まず、以下のライブラリが必要です(Python標準ライブラリを使用するため、追加インストールは不要です)。

  • imaplib:受信メールを取得(IMAP)
  • email:MIME形式のパース
  • smtplib:送信処理(SMTP)

基本スクリプト:受信+返信処理

import imaplib
import smtplib
import email
from email.mime.text import MIMEText
from email.header import decode_header
import time

# アカウント情報
EMAIL = "youraddress@example.com"
PASSWORD = "yourpassword"
IMAP_SERVER = "imap.example.com"
SMTP_SERVER = "smtp.example.com"
SMTP_PORT = 587

def connect_imap():
    mail = imaplib.IMAP4_SSL(IMAP_SERVER)
    mail.login(EMAIL, PASSWORD)
    mail.select("inbox")
    return mail

def fetch_unread_emails(mail):
    status, messages = mail.search(None, '(UNSEEN)')
    email_ids = messages[0].split()
    return email_ids

def extract_sender(msg):
    from_header = msg.get("From")
    return email.utils.parseaddr(from_header)[1]

def send_reply(to_address, subject):
    reply = MIMEText("お問い合わせありがとうございます。内容を確認いたしました。")
    reply["Subject"] = "Re: " + subject
    reply["From"] = EMAIL
    reply["To"] = to_address

    with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
        server.starttls()
        server.login(EMAIL, PASSWORD)
        server.send_message(reply)

def auto_reply():
    mail = connect_imap()
    email_ids = fetch_unread_emails(mail)

    for eid in email_ids:
        status, data = mail.fetch(eid, "(RFC822)")
        raw_email = data[0][1]
        msg = email.message_from_bytes(raw_email)

        subject, _ = decode_header(msg["Subject"])[0]
        if isinstance(subject, bytes):
            subject = subject.decode()

        sender = extract_sender(msg)
        send_reply(sender, subject)
        print(f"{sender} に返信を送信しました")

    mail.logout()

# 1回だけ実行する場合
auto_reply()

# 定期実行したい場合はループ
# while True:
#     auto_reply()
#     time.sleep(300)  # 5分ごとに確認

メールサービスごとの設定例

Gmailの場合:

  • IMAPサーバー:imap.gmail.com
  • SMTPサーバー:smtp.gmail.com
  • アプリパスワードの発行が必要(2段階認証ON時)

セキュリティへの配慮

  • パスワードは環境変数や別ファイルで管理するのが安全です
  • 不特定多数に返信する用途では、返信制限やフィルタ処理を実装するのが望ましいです

まとめ

Pythonを使えば、メールの受信監視と自動返信を簡単に実装できます。基本構成を応用することで、問い合わせ対応の自動化や、応募受付のリアクション送信など、さまざまな業務に活用できます。今後は件名や本文の解析、添付ファイルの処理なども加えることで、より高度な自動応答システムを構築することができます。