-1

以下是我连接到 SMTP 服务器并发送邮件的脚本。

from smtplib import SMTP
import datetime

debuglevel = 0

smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('smtp.gmail.com', 26)
smtp.login('ashwini.jena@gmail.com', 'Pa***wd')

from_addr = "Ashwin<ashwini.jena@gmail.com>"
to_addr = "foo@bar.com"

subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

message_text = "Hello\nThis is a mail from your server\n\nBye\n"

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"%( from_addr, to_addr, subj, date, message_text )

smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()

但它会引发以下错误:-

Traceback (most recent call last):
  File "C:\Python33\Bidhoo.py", line 15, in <module>
    smtp.connect('smtp.gmail.com', 26)
  File "C:\Python33\lib\smtplib.py", line 317, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:\Python33\lib\smtplib.py", line 288, in _get_socket
    self.source_address)
  File "C:\Python33\lib\socket.py", line 424, in create_connection
    raise err
  File "C:\Python33\lib\socket.py", line 415, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

请帮助我找到此错误的根本原因。也有人可以共享替代代码来连接到 SMTP ..

4

1 回答 1

2

我认为这在 smtp.connect 线上失败了?您可以通过在 Python 解释器中逐行运行脚本来验证这一点。

失败的原因是端口号不正确。而不是 26,尝试 587 看看会发生什么。

smtp.connect('smtp.gmail.com', 587)

至于替代脚本,我通过谷歌搜索找到了一些脚本。这是一个

于 2013-01-11T07:20:17.623 回答