问题描述
TimeoutError:[WinError 10060]连接尝试失败,因为一段时间后连接方未正确响应,或者由于连接的主机未能响应,建立的连接失败
这是我的代码:
import smtplib
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
server = smtplib.SMTP('smtp.gmail.com',25)
server.connect("smtp.gmail.com",465)
server.ehlo()
with open('password.txt','r') as f:
password = f.read()
server.login('[email protected]',password)
msg = MIMEMultipart()
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'Mail testing with Python'
with open('message.txt','r') as f:
message = f.read()
msg.attach(MIMEText(message,'plain'))
text = msg.as_string()
server.sendmail('[email protected]','[email protected]',text)
解决方法
首先,要使gmail与python脚本一起正常使用,您需要配置gmail以允许低安全性应用程序。我认为您已经完成了这部分,否则您可以查看gmail帮助。
Gmail help on turn on less secure app
这是应该发送电子邮件的脚本:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
server = smtplib.SMTP_SSL('smtp.gmail.com',465)
server.ehlo()
server.login('[email protected]',"your password")
msg = MIMEMultipart('alternative',)
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg['Subject'] = 'Mail testing with Python'
with open('message.txt','r') as f:
message = f.read()
msg.attach(MIMEText(message,'plain'))
text = msg.as_string().encode('utf8')
server.sendmail('[email protected]','[email protected]',text)