smtplib error: Name or Service unknown - python

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.

Related

Pyhton3 - send email failing with - "OSError: [Errno 113] No route to host"

I've script written in Python3, it's doing couple of things and one of them is sending email. That's the code:
import smtplib
import os
import json
import re
from datetime import datetime
from smtplib import SMTP
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_mail():
message = MIMEMultipart()
message['Subject'] = mailtitle
message['From'] = mailfrom
message['To'] = mailto
body_content = ("Text message")
message.attach(MIMEText(body_content, 'plain'))
msg_body = message.as_string()
server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(message['From'], message['To'], msg_body)
server.quit()
It's working fine on my virtual box environment but when I've put it on real testing environment I'm getting below output:
Traceback (most recent call last):
File "send_email.py", line 166, in <module>
send_mail()
File "send_email.py", line 159, in send_mail
server = smtplib.SMTP('localhost')
File "/usr/lib64/python3.6/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib64/python3.6/smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib64/python3.6/smtplib.py", line 307, in _get_socket
self.source_address)
File "/usr/lib64/python3.6/socket.py", line 724, in create_connection
raise err
File "/usr/lib64/python3.6/socket.py", line 713, in create_connection
sock.connect(sa)
OSError: [Errno 113] No route to host
Could you pls advise what can cause the issue? Firewall settings? Missing libraries?
Many thanks
I resolved that issue in the end. The problem was related to the blocked SMTP port 25 on the firewall. When the port has been opened, my issue disappeared.

send email with email module in python

when I try to send an email with email module I get error
I tried with 3 different mail provider
and it is my code :
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
message = MIMEMultipart()
message["from"] = "Amir Mohammad Fallah"
message["to"] = "*******#gmail.com"
message["subject"] = "python test message"
message.attach(MIMEText("body"))
password = "*******"
user = "*********#gmail.com"
with smtplib.SMTP("smtp.gmail.com", 465) as smtp: # port 587 for icloud and 25 for aol
smtp.ehlo()
smtp.login(user, password)
smtp.send_message(message)
print("it's Done !")
and I after while I got this errors :
Traceback (most recent call last):
File "/Users/mgxc2/PycharmProjects/Advance/Python.py", line 588, in <module>
with smtplib.SMTP("smtp.gmail.com", 465) as smtp: # port 587 for icloud and 25 for aol #mail.cortatech.ir port 587
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 338, in connect
(code, msg) = self.getreply()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/smtplib.py", line 394, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
First and foremost I think you should change with smtplib.SMTP("smtp.gmail.com", 465) to with smtplib.SMTP("smtp.gmail.com", 587) and see what happens... Secondly, you should change your Internet connection, because your code looks okay to me.. but I'll check it soon to know the cause, but first try the corrections I sent across
You should use port 587 because it's the default mail submission port.
Here is an articles that explain witch SMTP port to use for witch action.

How to reslove "socket.gaierror" error of python-smtplib?

Few hours back I have posted a post related to "Django email sending API" and its error. So I thought that first I should try something with "smtplib". Unfortunately, after struggling with "smtplib", I realise that it will also not work, because something is wrong with my code or my network or my machine which I am not able to figure out.
Can any body help me regarding to this?
As of now, after struggling a lot, I have tried hundreds of solution posted here and there and also I have tried to resolve with myself but nothing is working in my case kindly help.
Code is given bellow.
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import socks
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "172.16.0.2", '8084')
socks.wrapmodule(smtplib)
#smtp = smtplib.SMTP()
msg = MIMEMultipart()
msg['From'] = 'my#yahoo.com'
msg['To'] = 'example#gmail.com'
msg['Subject'] = 'simple email in python'
message = 'here is the email'
msg.attach(MIMEText(message))
mailserver = smtplib.SMTP('smtp.mail.yahoo.com',465)
# identify ourselves to smtp gmail client
mailserver.ehlo()
# secure our email with tls encryption
mailserver.starttls()
# re-identify ourselves as an encrypted connection
mailserver.ehlo()
mailserver.login('my#yahoo.com', 'pswd12345678')
mailserver.sendmail('my#yahoo.com','example#gmail.com',msg.as_string())
mailserver.quit()
This is the error coming again and again:
Traceback (most recent call last):
File "import_mail.py", line 21, in <module>
mailserver = smtplib.SMTP('smtp.mail.yahoo.com',465)
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -3] Temporary failure in name resolution
This error is raised as the 'EMAIL_BACKEND' definition is missing from the settings file. Make sure that the settings.py file contains the following line:-
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
IF you`re using the gmail account to set up a default interactive mail, use the following values:-
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587 #PORT NO
EMAIL_HOST_USER = #e-MAIL ID
EMAIL_HOST_PASSWORD = #PASSWORD
My system had not a DNS configured and I resolved this issue configuring a google DNS or an openDNS.

How can a socket error be addressed when e-mailing in Python from local host (without login to an STMP server)?

I'm writing a small e-mailing script that is intended to be used by a group of trusted people. After a long job that has been run by one of these people has completed, this script could run and send a simple e-mail with details on the job results. I do not want the script to try to log into an existing e-mail account on an STMP server, I want the e-mail sent simply from the computer on which the script is run.
When I try to run using localhost, I encounter a socket error:
Traceback (most recent call last):
File "./1_email.py", line 45, in <module>
main()
File "./1_email.py", line 34, in main
server = smtplib.SMTP("localhost")
File "/usr/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/lib/python2.7/socket.py", line 575, in create_connection
raise err
socket.error: [Errno 111] Connection refused
What am I doing wrong here?
#!/usr/bin/env python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def main():
message = MIMEMultipart("alternative")
message["Subject"] = "test"
message["From"] = "monitor#localhost"
message["To"] = "test#sern.ch"
text = "hello world"
html = """\
<html>
<head></head>
<body>
<p>
hello world
</p>
</body>
</html>
"""
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)
try:
server = smtplib.SMTP("localhost")
server.sendmail(
message["From"],
message["To"],
message.as_string()
)
server.quit()
except smtplib.SMTPException:
print("e-mail send error")
if __name__ == "__main__":
main()

Do I need to add specific information to send mail through python?

I am using the following code below:
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
#...
def send_file_zipped(the_file, recipients, sender='email#email.com'):
myzip = open('file.zip', 'rb')
# Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(myzip.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip')
themsg.attach(msg)
themsg = themsg.as_string()
# send the message
smtp = smtplib.SMTP("smtp.gmail.com", "587")
smtp.connect()
smtp.sendmail(sender, recipients, themsg)
smtp.close()
#running this
send_file_zipped('file.zip', 'email#email.edu')
I have tried different variations to try and make it connect successfully here, but I am at a loss here. The error I am getting is this:
Traceback (most recent call last):
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 99, in <module>
send_file_zipped('file.zip', 'email#email.com')
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 40, in send_file_zipped
smtp.connect()
File "/usr/local/lib/python3.2/smtplib.py", line 319, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python3.2/smtplib.py", line 294, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.2/socket.py", line 404, in create_connection
raise err
File "/usr/local/lib/python3.2/socket.py", line 395, in create_connection
sock.connect(sa)
socket.error: [Errno 61] Connection refused
I am going to assume that my issue lies in connecting with the smtp server, but I don't know what I am missing. Any help would be greatly appreciated!!
smtp.connect() is wrong/redundant. The smtplib.SMTP(...) calls .connect upon initialization. A bare .connect call without any parameters means connection to localhost and if you do not have a SMTP server running on your machine you'll get an error.
However your goal is to send mail through GMail. Note that GMail's SMTP requires authentication, which you are not doing.
Your last lines should be accordingly:
# send the message
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.helo()
smtp.starttls() # Encrypted connection
smtp.ehlo()
smtp.login(username, password) # Give your credentials
smtp.sendmail(sender, recipients, themsg)
smtp.quit()
This may not be your problem, but you're specifying the port number as a string, and that's probably not going to work.

Categories