我正在尝试使用以下脚本发送代理服务器后面的电子邮件。
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。任何帮助都将不胜感激。
应该可以了:
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 35882577n8BITMIMEnSTARTTLSnAUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKENnENHANCEDSTATUSCODESnCHUNKINGnSMTPUTF8')
In [5]: server.starttls()
Out[5]: (220, b'2.0.0 Ready to start TLS')
确保您的网络允许连接到该主机的587端口