简体   繁体   中英

smtplib error: Name or Service unknown

I'm trying to use the following script to send an email behind a proxy server.

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()

It gives the following error:

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

I have already set the http_proxy environment variable and fetching webpages using urllib2 in python works but not smtplib. Any help will be appreciated.

That should work:

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')

Make sure your network allows connections to port 587 at this host.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM