我有一台安装了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"也可以正常工作,端口是打开的。
Postfix配置文件:
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = localhost
mynetworks = 127.0.0.0/8
myorigin = /etc/mailname
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()