【问题标题】:Unable to send mail using smtplib in python无法在 python 中使用 smtplib 发送邮件
【发布时间】:2020-01-31 19:50:33
【问题描述】:

我在 Ubuntu 操作系统中运行以下代码。当我在独立机器上运行此代码时,我没有收到任何错误。 但是当我连接远程机器并运行相同的代码时,我收到以下错误消息。 我还修改了端口值并尝试了多次,但问题没有解决。我想知道我需要在哪里检查才能解决问题。

import smtplib
message = ' '
sender  = ' '
receivers = ' '
SUBJECT  = ' '
TEXT     = ' '
sender = 'sender1@abc.com'
receivers = ['rec1@abc.com','rec2@abc.com']

# prepare message
SUBJECT = "Test mail "
TEXT    = """Message line1 \n
             Message line2 \n  """

message  = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)

try:
    smtpObj = smtplib.SMTP(<Value>)
    smtpObj.sendmail(sender, receivers, message)
    smtpObj.close()

except smtplib.SMTPConnectError:
       print "Error: unable to send email"

except smtplib.SMTPException:
       print "Error: unable to send email"

错误信息:

Traceback (most recent call last):
  File "sampa.py", line 23, in <module>
    smtpObj = smtplib.SMTP(<Value>)
  File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python2.7/smtplib.py", line 316, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
    return socket.create_connection((host, port), timeout)
  File "/usr/lib/python2.7/socket.py", line 571, in create_connection
    raise err
socket.error: [Errno 111] Connection refused

【问题讨论】:

  • 您审查了&lt;Value&gt;,这就是您收到错误的原因。确保您可以访问端口 25 上的&lt;Value&gt;。由于多种原因,可能无法从端口 25 上的“远程机器”访问该服务器……网络问题、防火墙、路由等……

标签: python email smtp smtplib


【解决方案1】:
try:
    smtpObj = smtplib.SMTP(smtp_server, port)
    smtpObj.ehlo()  # Can be omitted
    smtpObj.starttls(context=context)  # Secure the connection
    smtpObj.ehlo()  # Can be omitted
    smtpObj.login(sender, password)
    smtpObj.sendmail(sender, receivers, email_text)

【讨论】:

  • 感谢您的回复。这是服务器问题。一段时间后我们尝试了相同的代码,它成功了:)
猜你喜欢
  • 2013-11-05
  • 2017-09-20
  • 2010-10-07
  • 2014-01-31
  • 2021-04-26
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 2023-03-10
相关资源
最近更新 更多