sendmail成功,但python smtplib无法连接

时间:2011-09-08 20:16:18

标签: python linux email ubuntu smtp

这有效:

printf 'hi' | sendmail -f myname@example.com myname@example.com

但失败了:

def send_mail(send_from, send_to, subject, text, files=[ ], server="localhost"):
    assert type(send_to)==list
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach( MIMEText(text) )
    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(f, "r").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)
    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

输出:

Traceback (most recent call last):
  File "send_mail.py", line 50, in <module>
    send_mail(send_from, send_to, subject, text, files )
  File "send_mail.py", line 35, in send_mail
    smtp = smtplib.SMTP(server)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 242, in __init__
    (code, msg) = self.connect(host, port)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 302, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/smtplib.py", line 277, in _get_socket
    return socket.create_connection((port, host), timeout)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 571, in create_connection
    raise err
socket.error: [Errno 61] Connection refused

如何让send_mail方法正常工作?

1 个答案:

答案 0 :(得分:0)

重新发布提出问题的用户的回答:

实际上,127.0.0.1:25没有任何约束。启动smtpd解决了这个问题。 @Adam Rosenfield - 是的,它是同一台服务器。 - lugbug 2011年9月8日22:49