我正在尝试使用以下脚本在代理服务器后面发送电子邮件。
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import sys
import urllib2
fromaddr = "abc@gmail.com"
toaddr = "xyz@gmail.com"
cc = "123@gmail.com"
toaddrs = toaddr + cc
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "subject"
body = "body"
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login("user", "pass")
text = msg.as_string()
server.sendmail(fromaddr, toaddrs, text)
server.close()
它出现以下错误:
Traceback (most recent call last):
File "script.py", line 18, in <module>
server = smtplib.SMTP('smtp.gmail.com:587')
File "/usr/lib/python2.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 311, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 286, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 553, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
我已经设置了http_proxy环境变量并在python中使用urllib2获取网页但不是smtplib。任何帮助将不胜感激。
答案 0 :(得分:0)
这应该有效:
In [1]: import smtplib
In [2]: server = smtplib.SMTP('smtp.gmail.com:587')
In [3]: server
Out[3]: <smtplib.SMTP at 0x7f80fbaa0ba8>
In [4]: server.ehlo()
Out[4]:
(250,
b'mx.google.com at your service, [46.237.207.180]\nSIZE 35882577\n8BITMIME\nSTARTTLS\nAUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN\nENHANCEDSTATUSCODES\nCHUNKING\nSMTPUTF8')
In [5]: server.starttls()
Out[5]: (220, b'2.0.0 Ready to start TLS')
确保您的网络允许连接到此主机的端口587.