有人可以告诉我为什么我从下面的代码中收到SMTPServerDisconnected(“连接意外关闭”)错误吗?
import smtplib
from string import Template
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
MY_ADDRESS = '---'
PASSWORD = '---'
def get_contacts(filename):
"""
Return two lists names, emails containing names and email
addresses
read from a file specified by filename.
"""
names = []
emails = []
with open(filename, mode='r', encoding='utf-8') as contacts_file:
for a_contact in contacts_file:
names.append(a_contact.split()[0])
emails.append(a_contact.split()[1])
return names, emails
def read_template(filename):
"""
Returns a Template object comprising the contents of the
file specified by filename.
"""
with open(filename, 'r', encoding='utf-8') as template_file:
template_file_content = template_file.read()
return Template(template_file_content)
def main():
names, emails = get_contacts('contacts.txt') # read contacts
message_template = read_template('message.txt')
# set up the SMTP server
s = smtplib.SMTP('smtp.gmail.com', 465)
s.ehlo()
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
# For each contact, send the email:
for name, email in zip(names, emails):
msg = MIMEMultipart() # create a message
# add in the actual person name to the message template
message =
message_template.substitute(PERSON_NAME=name.title())
# Prints out the message body for our sake
print(message)
# setup the parameters of the message
msg['From']=MY_ADDRESS
msg['To']=email
msg['Subject']="This is TEST"
# add in the message body
msg.attach(MIMEText(message, 'plain'))
# send the message via the server set up earlier.
s.send_message(msg)
del msg
# Terminate the SMTP session and close the connection
s.quit()
if __name__ == '__main__':
main()
很明显,当我运行代码时,我的地址和密码已填写。
在终端中运行时得到的回溯是:
回溯(最近通话最近): 在第71行中输入文件“ emailAlert2.py” 主要() 主文件“ emailAlert2.py”,第40行 s = smtplib.SMTP('smtp.gmail.com',465) init 中的文件“ /usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py”,第251行 (代码,信息)= self.connect(主机,端口) 在连接中的文件“ /usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py”中,行338 (代码,味精)= self.getreply() 在getreply中的文件“ /usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py”,行394 引发SMTPServerDisconnected(“连接意外关闭”) smtplib.SMTPServerDisconnected:连接意外关闭
谢谢
答案 0 :(得分:0)
Google Gmail服务器正在挂断您的电话(放弃连接尝试)。
如果您已启用对Gmail帐户的第三方访问(link),请按以下步骤更改代码:
s = smtplib.SMTP('smtp.gmail.com', 465)
s.ehlo()
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
更改为此:
s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
s.ehlo()
s.login(MY_ADDRESS, PASSWORD)
挂断的原因是您正在使用未加密的方法(smtplib.SMTP())创建连接。 Google希望您使用需要SSL的SMTPS进行连接。
答案 1 :(得分:0)
尝试使用端口号 587 代替s = smtplib.SMTP('smtp.gmail.com', 465)
答案 2 :(得分:-1)
可能您需要提供应用密码而不是默认密码 - 看看这个 - https://support.google.com/accounts/answer/185833