【发布时间】:2023-02-08 03:45:06
【问题描述】:
我在 python 中编写了一个基本函数,使用 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 服务器才能发送此电子邮件。
【问题讨论】: