我使用Twisted
实现了python SMTP服务器和客户端。当我在本地测试它们时,即使用localhost,一切都很完美。但是,我想在分布式环境中检查它。因此,我运行了一个EC2 Amazon实例,我在其上启动了我的SMTP服务器作为应用程序,如下所示
factory = StdoutSMTPFactory("./tmp/mail")
tcp_server = internet.TCPServer(2500, factory)
application = service.Application("SMTPServer")
tcp_server.setServiceParent(application)
其中StdoutSMTPFactory
是我的工厂构建我的SMTP服务器的实现。
我的SMTP客户端如下所示:
import sys
from email.mime.text import MIMEText
from twisted.internet import reactor
from twisted.mail.smtp import sendmail
from twisted.python import log
log.startLogging(sys.stdout)
host = "ec2-X-X-X-X.eu-west-1.compute.amazonaws.com"
sender = "secretsender@example.com"
recipients = ["ubuntu@ec2-X-X-X-X.eu-west-1.compute.amazonaws.com"]
msg = MIMEText("""Test message
from SenderX
""")
msg["Subject"] = "Title"
msg["From"] = '"Secret Sender" <%s>' % (sender,)
msg["To"] = ", ".join(recipients)
deferred = sendmail(host, sender, recipients, msg.as_string(), port=2500)
deferred.addBoth(lambda result: reactor.stop())
reactor.run()
其中ec2-X-X-X-X.eu-west-1.compute.amazonaws.com
当然是我的EC2实例的有效主机名,只是为帖子隐藏了。
当我尝试向我的实例发送电子邮件时,我获得以下内容:
[-] Log opened.
[-] Starting factory <twisted.mail.smtp.ESMTPSenderFactory instance at 0x10815d638>
[Uninitialized] SMTP Client retrying server. Retry: 5
[Uninitialized] SMTP Client retrying server. Retry: 4
[Uninitialized] SMTP Client retrying server. Retry: 3
[Uninitialized] SMTP Client retrying server. Retry: 2
[Uninitialized] SMTP Client retrying server. Retry: 1
[-] Stopping factory <twisted.mail.smtp.ESMTPSenderFactory instance at 0x10815d638>
[-] Main loop terminated.
服务器或客户端都没有错误。只是看起来客户端无法连接到服务器。有人可以建议我做错了什么吗?
答案 0 :(得分:0)
您的代码中包含:
deferred.addBoth(lambda result: reactor.stop())
这是同步Python代码的延迟等价物:
try:
...
except:
pass
reactor.stop()
如果您想查看错误,请在Deferred上对传递给errback的参数执行某些操作。
from twisted.logger import Logger
logger = Logger()
deferred.addErrback(partial(logger.failure, "sending mail"))
deferred.addCallback(lambda ignored: reactor.stop())
或者考虑使用react
from twisted.internet.task import react
def main(reactor):
...
return sendmail(host, sender, recipients, msg.as_string(), port=2500)
react(main, [])
将为您执行错误报告。