python 发送电子邮件 - ConnectionRefusedError: [Errno 111] 连接被拒绝。请提出一些想法

问题描述 投票:0回答:2

我在 python 中编写了一个基本函数,通过 localhost 使用 smtp 发送电子邮件,但它一直失败,但是另一个脚本使用相同的代码可以正常工作。

我的功能:


def send_email_err():

    sender = '[email protected]'
    receivers = ['[email protected]']

    message = """From: From Person <[email protected]>
    To: To Person <[email protected]>
    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
2个回答
1
投票
  • 第一个TB:您忘记启动服务器。旋转第二个终端并运行

    python -m smtpd -n -c DebuggingServer host:port
    (如果您在本地设备上运行它并测试功能)

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

    from smtplib import SMTPException

你很紧张,放松一下:)


0
投票

现在建议使用 https://aiosmtpd.readthedocs.io/en/latest/cli.html 代替。

因为:

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

© www.soinside.com 2019 - 2024. All rights reserved.