Pythonからメール送信

ワンライナーで立てたDebugingServerにpythonからメール投げてみる

pythonワンライナーでテスト用smtpサーバーをたてる - brainstorm

from email.message import Message
from email.utils import formatdate, make_msgid
import smtplib


def create_message(fromaddr, toaddr, subject, body):
    msg = Message()
    msg['To'] = fromaddr
    msg['From'] = toaddr
    msg['Subject'] = subject
    msg['Date'] = formatdate(localtime=True)
    msg['Message-ID'] = make_msgid()
    msg.set_payload(body)
    return msg.as_string()


def send(fromaddr, toaddr, message):
    s = smtplib.SMTP(host="127.0.0.1", port=20025)
    s.sendmail(fromaddr, [toaddr], message)
    s.close()

if __name__ == '__main__':
    fromaddr = 'foo@example.com'
    toaddr = 'bar@example.com'
    message = create_message(fromaddr, toaddr, 'test subject', 'test body')
    send(fromaddr, toaddr, message)

DebuggingServer側の出力

---------- MESSAGE FOLLOWS ----------
To: foo@example.com
From: bar@example.com
Subject: test subject
Date: Sat, 23 Feb 2013 16:22:00 +0900
Message-ID: <20130223072200.5386.98275@xxxxxxxxxxxxxx>
X-Peer: 127.0.0.1

test body
------------ END MESSAGE ------------