[英]python sending email - ConnectionRefusedError: [Errno 111] Connection refused. Please suggest some ideas
我在 python 中编写了一个基本函数来使用带有 localhost 的 smtp 发送电子邮件,但它一直失败,但是另一个脚本使用相同的代码可以正常工作。
我的功能:
def send_email_err():
sender = 'sender@test.com'
receivers = ['receiver@test.com']
message = """From: From Person <sender@test.com>
To: To Person <receiver@test.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print ("Successfully sent email")
except SMTPException:
print ("Error: unable to send email")
send_email_err()
我得到的错误是:
Traceback (most recent call last):
File "./send_email.py", line 147, in send_email_err
smtpObj = smtplib.SMTP('localhost')
File "/usr/lib64/python3.6/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib64/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib64/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./send_email.py", line 159, in <module>
send_email_err()
File "./send_email.py", line 150, in send_email_err
except SMTPException:
NameError: name 'SMTPException' is not defined
我们是否需要在我执行此脚本的主机上运行 smtp 服务器才能发送此电子邮件。
First tb:您忘记启动服务器。 打开第二个终端并运行python -m smtpd -n -c DebuggingServer host:port
如果您在本地设备上运行它并测试功能
第二个错误:您忘记from smtplib import SMTPException
放松你紧张,放松:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.