首页 > 解决方案 > Python smtplib.SMTP('localhost') 永远挂起

问题描述

我有一台安装了 Postfix SMTP 服务的服务器,我可以使用 bash 发送消息,如下所示:

echo "This is the body of the email" | mail -s "This is the subject line" user@example.com

但是当我尝试对 Python 做同样的事情时,它会永远挂起:

import smtplib
s = smtplib.SMTP('localhost')
s.send_message('')

脚本挂在第二行,不清楚原因。我检查了 iptables 的配置(它是空的),我仍然可以使用 bash 命令发送消息。

“telnet localhost 25”也可以正常工作,端口是开放的。

后缀配置文件:

mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = localhost
mynetworks = 127.0.0.0/8
myorigin = /etc/mailname

标签: postfix-mtasmtplib

解决方案


send_message()需要一个EmailMessage而不是字符串。目前它似乎挂起,因为 postfix 正在等待你告诉它做某事,你可以使用set_debuglevel()启用调试输出。

这是一个应该有效的简单示例:

from email.message import EmailMessage
import smtplib

msg = EmailMessage()
msg["From"] = "user@example.com"                                                    
msg["To"] = "another-user@example.com"
msg["Subject"] = "Test message subject."                                            
msg.set_content("Test message.")                                                    

s = smtplib.SMTP("localhost")
s.set_debuglevel(1)
s.send_message(msg)
s.quit()

推荐阅读