【问题标题】:python sending email - ConnectionRefusedError: [Errno 111] Connection refused. Please suggest some ideaspython 发送电子邮件 - ConnectionRefusedError:[Errno 111] 连接被拒绝。请提出一些想法
【发布时间】: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 服务器才能发送此电子邮件。

【问题讨论】:

    标签: python email smtp


    【解决方案1】:
    • 首先要注意的是:您忘记启动服务器了。打开第二个终端并运行 python -m smtpd -n -c DebuggingServer host:port 如果你在本地设备上运行它并测试功能

    • 第二个错误:您忘记导入 SMTPException from smtplib import SMTPException

    放松你紧张,放松 :)

    【讨论】:

      【解决方案2】:

      现在建议改用https://aiosmtpd.readthedocs.io/en/latest/cli.html

      因为:

      deprecationWarning:asynchat 模块已弃用,将在 Python 3.12 中删除。推荐的替代品是 asyncio

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-08
        • 1970-01-01
        • 2017-04-10
        • 2016-07-08
        • 2012-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多