我正在尝试使用python中的smtp库发送电子邮件。但问题是由于代理服务器(需要身份验证)在我的大学中使用,代码无法正常工作。我收到以下错误:
Traceback (most recent call last):
File "mail.py", line 41, in <module>
"10.jpg")
File "mail.py", line 29, in mail
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
File "/usr/lib/python2.7/smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 101] Network is unreachable
以下是代码:
#!/usr/bin/python
import smtplib
from email import Encoders
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
import os
USER = "...."
PASSWORD = "...."
def mail(to, subject, text, attach):
msg = MIMEMultipart()
msg['From'] = USER
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition','attachment; filename="%s"' %os.path.basename(attach))
msg.attach(part)
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(USER, PASSWORD)
mailServer.sendmail(USER, to, msg.as_string())
mailServer.close()
mail("yrishabh24@gmail.com",
"BB Testing",
"This is a email sent with python",
"10.jpg")
我该如何解决这个问题?