Python smtplib Name or service not known - python

i was making a simple daemon in python which takes a mail queue and delivers them to the recipients. Everything is working pretty good except from the smtplib which is actually the most important part.
What happens?
When im running the script im getting the following error:
root#vagrant-ubuntu-trusty-64:/mailer/tests# python daemon_run.py
[Errno -2] Name or service not known
From what i found on the internet this error occurs when it cant connect to the SMTP server. Most users suggested fixes on postman which i dont use since i take advantage of google's services.
The code
headers = "\r\n".join(["from: " + "my_email#gmail.com",
"subject: " + "Testing",
"to: " + "recipient#gmail.com",
"mime-version: 1.0",
"content-type: text/html"])
content = headers + "\r\n\r\n" + template_content
server = smtplib.SMTP('smtp.google.com', 587)
server.ehlo()
server.starttls()
server.login('my_email#gmail.com', 'pass')
server.sendmail('my_email#gmail.com', 'recipient#gmail.com', content)
server.close()
Please note that i'm using exactly the same login details in PHPMailer which actually works.
Any ideas?

It seems like the goold old typo hit again. Gmail's SMTP is smtp.gmail.com and not smtp.google.com

Related

Gmail SMTP server has stopped sending emails after I rebooted it

I have tried to use flask_mail to send emails via gmail SMTP. I want to simply send an email back to the host with some details.
I have set the following settings
app = Flask(__name__)
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'fakeemail#gmail.com'
app.config['MAIL_PASSWORD'] = 'fakepassword'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
And wrote the following code to send
def send_email(senders_email, senders_subject, senders_feedback):
print("email " + senders_email)
print("sub " + senders_subject)
print("feed " + senders_feedback)
msg = Message('Feedback from ' + senders_email, sender='fakeemail#gmail.com',
recipients=['fakeemail#gmail.com'])
print("message defined")
msg.body = "Users Subject: " + senders_subject + "\n" + "Users Feedback: " + senders_feedback
print("body set")
mail.send(msg)
print("message sent")
At first I was getting successful emails which sent the specific email to me but now I get a 500 error after about 20 or 30 seconds
OSError: [Errno 101] Network is unreachable
Any help would be appreciated
I came across a quite similar problem and it turned out the problem is caused by the mail port you are using (465). The Bluehost has blocked this port to discourage spam. Detailed information is available with the link:
https://my.bluehost.com/cgi/help/500
It seems that maybe you either need to buy their service (which might still not be working, because the port is also blocked for a dedicated IP) or try to find a detour. In my own case, I changed SMTP to the E-mail address I use at the university since the website is just an intern thing.

How to create a free SMTP server

I am not at all familiar with SMTP but I am working on sending emails through Python code. I have the code but I need to pass SMTP host name for it to actually work. Is there any service which provides a free SMTP service that I leverage for testing out my code? I looked around to create my own SMTP server but couldn't find something that provides a step by step guide to create a SMTP server. I want to create a free server(or if there is any free service) that will provide me with a host name(ip address) so that I can put that host name in my python code and execute it from any machine.
If anyone can point me in the right direction it will be helpful.
import smtplib
username = 'user'
password = 'pwd'
from_addr = 'username#gmail.com'
to_addrs = 'username#gmail.com'
msg = "\r\n".join([
"From: username#gmail.com",
"To: username#gmail.com",
"Subject: subject",
"",
"message"
])
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(from_addr, to_addrs, msg)
server.quit()
You can use mutt linux command also here.
See :
https://docs.python.org/3/library/smtplib.html
https://support.google.com/a/answer/176600?hl=en
You need service like https://mailtrap.io/. You'll get SMTP server address (eventually port number) that you point your application to. All e-mails produced by your application will be then intercepted by mailtrap (thus not delivered to the real To: address).
They offer free variant that seems to be suitable for your needs.

Python 2: SMTPServerDisconnected: Connection unexpectedly closed

I have a small problem with sending an email in Python:
#me == my email address
#you == recipient's email address
me = "some.email#gmail.com"
you = "some_email2#gmail.com"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Alert"
msg['From'] = me
msg['To'] = you
# Create the body of the message (a plain-text and an HTML version).
html = '<html><body><p>Hi, I have the following alerts for you!</p></body></html>'
# Record the MIME types of both parts - text/plain and text/html.
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('aspmx.l.google.com')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
So before now, my program didn't give me an error, but it also didn't send me an email. And now python gives me an error:
SMTPServerDisconnected: Connection unexpectedly closed
How can I fix this?
TLDR: switch to authenticated connection over TLS.
Most probably the gmail server rejected the connection after the data command (very nasty of them to do so at this stage :). The actual message is most probably this one:
retcode (421); Msg: 4.7.0 [ip.octets.listed.here 15] Our system has detected an unusual rate of
4.7.0 unsolicited mail originating from your IP address. To protect our
4.7.0 users from spam, mail sent from your IP address has been temporarily
4.7.0 rate limited. Please visit
4.7.0 https://support.google.com/mail/answer/81126 to review our Bulk Email
4.7.0 Senders Guidelines. qa9si9093954wjc.138 - gsmtp
How do I know that? Because I've tried it :) with the s.set_debuglevel(1), which prints the SMTP conversation and you can see firsthand what's the issue.
You've got two options here:
Continue using that relay; as explained by Google, it's unencrypted gmail-to-gmail only, and you have to un-blacklist your ip through their procedure
The most fool-proof option is to switch to TLS with authentication
Here's how the changed source looks like:
# skipped your comments for readability
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
me = "some.email#gmail.com"
my_password = r"your_actual_password"
you = "some.email2#gmail.com"
msg = MIMEMultipart('alternative')
msg['Subject'] = "Alert"
msg['From'] = me
msg['To'] = you
html = '<html><body><p>Hi, I have the following alerts for you!</p></body></html>'
part2 = MIMEText(html, 'html')
msg.attach(part2)
# Send the message via gmail's regular server, over SSL - passwords are being sent, afterall
s = smtplib.SMTP_SSL('smtp.gmail.com')
# uncomment if interested in the actual smtp conversation
# s.set_debuglevel(1)
# do the smtp auth; sends ehlo if it hasn't been sent already
s.login(me, my_password)
s.sendmail(me, you, msg.as_string())
s.quit()
Now, if try to 'cheat' the system and send with a different (non-gmail) address it's gonna a) require you to connect to a different hostname (some of the MX records for gmail), then b) stop you and close the connection on the grounds of blacklisted ip, and c) do reverse DNS, DKIM and lots of other countermeasures to make sure you're actually in control of the domain you presented in the MAIL FROM: address.
Finally, there's also option 3) - use any other email relaying service, there are tons of good ones :)
I Had the same issue and solved it just by specifying the right port like this:
smtplib.SMTP('smtp.gmail.com', 587)
Using smtplib.SMTP_SSL() instead of smtplib.SMTP() works for me. Try this.
I have realised a strange behavior. I have used similar codes mentioned both the question and answers. My code has been working for the last days. However, today I encountered the error message mentioned in the question.
My solution:
I had tried my successful attempt via library network. Today I have tried it via Starbucks network (over captive portal). I changed it to my mobile network. It started working again.
Possibly, Google rejects requests from unreliable networks.
I was facing the same problem. In my case, password was changed just few days back. So, it was giving the error. As I updated the password in code, its working like a charm...!!!
Googlers: I had a test smtp server running locally. I was getting this error because I was shutting down the local smtp server before closing the client smtp.
with smtplib.SMTP_SSL("smtp.mail.yahoo.com", port=465) as connection:
connection.login(
user=my_email,
password=my_password
)
connection.sendmail(
from_addr=my_email,
to_addrs=friend_address,
msg=f"Subject:Text\n\n"
f"Body of the text"
)
This is my code. I hope it will be helpful.

Python script should send me mail when there is any exception

I want my Python script to send me mail me when there is any exception. I have tried some code related to SMTP that I found, but unfortunately it's not executing and showing an error. Please help me to find out the main problem.
The SMTP code:
import smtplib
import string
SERVER = 'localhost'
SUBJECT = "Test email from Python"
TO = "abc.def#defghij.com"
FROM = "python#mydomain.com"
text = "Sample of mail"
BODY = string.join(("From: %s" % FROM,"To: %s" % TO,"Subject: %s" %SUBJECT ,"",text), "\r\n")
server = smtplib.SMTP(SERVER) #Here in this line it showing error
server.sendmail(FROM,TO,BODY)
server.quit()
** error message * server = smtplib.SMTP(SERVER)
socket.error: (10047, 'Address family not supported by protocol family: See http://wiki.python.org/jython/NewSocketModule#IPV6addresssupport')
I tested this code with Jython 2.5.3 and Python 2.7 and it works if I change SERVER from localhost to real SMTP server. I took SMTP server address from my email client configuration.
You can try this with yagmail, it will make it all much more convenient:
from yagmail import SMTP
SMTP(FROM).send(TO, SUBJECT, text)
It really requires only that much, and if you do some setup you're registered and safe (no need to write your username and password in script).
Read more about it at github.

Sending an Email via Python

I'm attempting to send an email with Python. From what I can tell, all the following code needs is a valid recipient and a host HOST. I'm unsure on how to get the host. What is the simplest way?
import smtplib
import string
SUBJECT = "Test email from Python"
TO = "python#mydomain.com"
FROM = "python#mydomain.com"
text = "blah blah blah"
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT ,
"",
text
), "\r\n")
server = smtplib.SMTP(HOST)
server.sendmail(FROM, [TO], BODY)
server.quit()
The HOST is the SMTP relay provided by your ISP (typically related to the domain name of your from address). If you use a desktop mail client, you'll be able to see the SMTP server listed in your mail settings. If you're hosting using shared hosting, your hosting provider should be able to provide an SMTP server for you to use.
We are not in the position to tell you a valid mail host aka smtp server. You should know where to send your mail to: either ask your organization IT or ask your mail provider.

Categories

Resources