通过Python SMTP服务器发送邮件

时间:2013-12-10 15:01:48

标签: python smtp smtpd

我正在尝试构建一个小型SMTP服务器,通过它我可以发送一些消息。看着smtpd库发现有什么东西。但我只能创建一个服务器来读取收到的电子邮件,但从未将其发送到所请求的地址。

import smtpd
import asyncore

class CustomSMTPServer(smtpd.SMTPServer):

def process_message(self, peer, mailfrom, rcpttos, data):
    print 'Receiving message from:', peer
    print 'Message addressed from:', mailfrom
    print 'Message addressed to  :', rcpttos
    print 'Message length        :', len(data)
    return

server = CustomSMTPServer(('127.0.0.1', 1025), None)

asyncore.loop()

客户端:

import smtplib
import email.utils
from email.mime.text import MIMEText

# Create the message
msg = MIMEText('This is the body of the message.')
msg['To'] = email.utils.formataddr(('Recipient', 'recipient@example.com'))
msg['From'] = email.utils.formataddr(('Author', 'author@example.com'))
msg['Subject'] = 'Simple test message'

server = smtplib.SMTP('127.0.0.1', 1025)
server.set_debuglevel(True) # show communication with the server
try:
    server.sendmail('author@example.com', ['myadress@gmail.com'], msg.as_string())
finally:
    server.quit()

1 个答案:

答案 0 :(得分:3)

如果您真的想要这样做 然后查看Twisted示例:

http://twistedmatrix.com/documents/current/mail/examples/index.html#auto0

我真的不建议您编写自己的MTA(邮件传输代理),因为这是 一个复杂的任务,需要担心许多边缘案例和标准。

使用现有的MTA,例如Postfix,Exim或Sendmail。

相关问题