Sending email through gmail with Python - python

So I have tried at least 5-10 examples online to send an email, but I keep getting the same error.
Traceback (most recent call last):
File "C:/Users/alxu/Project/LogFilter.py", line 88, in ?
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
File "C:\Python24\lib\smtplib.py", line 244, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python24\lib\smtplib.py", line 292, in connect
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
socket.gaierror: (11004, 'getaddrinfo failed')
The last example I used code was like this...
import smtplib
to = 'mkyong2002#yahoo.com'
gmail_user = 'mkyong2002#gmail.com'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.close()
I am using Python 2.4.3.
EDIT: McAfee is has host intrusion prevention so all the times I attempted to do this it blocked it.

Since you are behind a corporate proxy, you can't directly connect to any outside server, you need to connect through the proxy. In this case, you're trying to connect to a SMTP server, which uses port 25 or 587. I assume you're behind a HTTP proxy that doesn't block SMTP ports. If your corporate proxy blocks these ports, then there's nothing you can do to connect to the server.
The smtplib module doesn't include the functionality to connect to a SMTP server through a proxy. As a workaround, I wrote the custom class ProxySMTP, which I have posted here along with instructions on how to use it.
Let me know if it works for you.

Your last example code should work. One thing you need to do is to make sure you allow access to less secure apps by going to the following link.
google settings for secure apps
The reason for this is google flags such automated email scripts as less secure. You should also be aware of the risks. Make sure you change this setting back if you are not gonna need it.

Related

I would like to define a server using smtplib on Python but an error occurred

A program I wanted to create requires to login to a mail server.
I was able to login using smtplib on Gmail, but it didn't work on Yahoo mail.
SMTP Port 465
Server mail: smtp.mail.yahoo.co.jp
python code on IDLE
import smtplib
smtp_obg = smtplib.SMTP("smtp.mail.yahoo.co.jp", 465)
Error message
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
smtp_obg = smtplib.SMTP("smtp.mail.yahoo.co.jp", 465)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py", line 253, in __init__
(code, msg) = self.connect(host, port)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py", line 341, in connect
(code, msg) = self.getreply()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/smtplib.py", line 398, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
I would appreciate if someone could help. Thank you in advance.
You must run login after creating smtp_obj (smtp_obg.login('username', 'password')). If you trying to login, please mention it.
You must activate SMTP feature at Yahoo's web page (Same as Gmail). Sorry for Japanese, but not sure if yahoo.co.jp is using somewhere outside Japan. :)
In English, this parameter should be called like: IMAP/POP/SMTP access and mail transfer
I checked my account. STMP access is disabled by default.
When you create a connection to your smtp server you need to know more about the server about what way you want to connect to it.
There are normal with and without SSL connection based on port number to your SMTP server.
I use this site https://settings.email/yahoo-co-jp-email-settings/ to get more info about your SMTP server you want to use from yahoo and it says the port 465 is an SSL connection so you need to connect with SSL connection else you can't sending out this way.
in smtplib in python you have smtplib.SMTP and smtplib.SMTP_SSL functions to work with, the first it's used when it's not SSL requirement, and the second its used when you need SSL like yahoo smtp.
Can you try out to use smtplib.SMTP_SSL function and see about its working for you?
import smtplib
smtp_obg = smtplib.SMTP_SSL("smtp.mail.yahoo.co.jp", 465)
Mabey its required a username and password to sending out, I did not have so much info about yahoo SMTP to can explain that part for you.

SMTPException: STARTTLS extension not supported by server

I am trying to send mail using python smtplib module, but I got error.
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.login("xxxxxxxx#gmail.com", "yyyyyyy")
message = "Message_you_need_to_send"
s.sendmail("xxxxxxxxx#gmail.com", "aaaaaaaaa#gmail.com", message)
s.quit()
I got error like below:
Traceback (most recent call last): File "/home/engineer/demo.py",
line 52, in
s.starttls() File "/usr/lib/python2.7/smtplib.py", line 637, in starttls
raise SMTPException("STARTTLS extension not supported by server.") SMTPException: STARTTLS extension not supported by server.
I refer the solution from another link. You may try to remove s.ehlo() before s.starttls().
I tested your code with my own gmail account, it seems the code should work with s.echlo(). You may like to check your gmail security setting eg enable Less secure apps, Let less secure apps use your account
You also enable debug by using s.set_debuglevel(1)
import smtplib
s = smtplib.SMTP('smtp.gmail.com', 587)
s.set_debuglevel(1)
s.ehlo()
s.starttls()
No changes as far as code is concerned, end up finding out, Issue was associated with enough firewall permissions.

Python smtplib Name or service not known

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

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.

Python SMTP, Gmail not responding

When I try to connect to the Gmail server, python throws an error:
>>> from smtplib import SMTP
>>> m = SMTP('smtp.gmail.com', 587)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27\lib\smtplib.py", line 309, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python27\lib\smtplib.py", line 284, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
socket.error: [Errno 10060]
The rest of the output is in a diferent language but it basically says that the host (gmail) didn't respond.
I can see my email on a browser here at my work, probably there's a network configuration that doesn't allow me to automate the email delivering.
Is there a work around to let python act as a regular browser?
First, you can only access gmail's SMTP servers as a client with some form of authentication; the recommended way is with oauth. See this page and this one for details. So, your code won't work, even when you get past this problem.
However, that doesn't explain why it's rejecting your connection before you even get a chance to log in.
The most likely possibility is that gmail's routers are maintaining a dynamic whitelist of IPs. When you use a properly-logged-in connection of some other kind, you get added to the whitelist for N seconds, meaning you're allowed to connect to port 587; otherwise, you're rejected. This would be similar to the traditional SMTP-after-IMAP auth scheme, but not restricted to IMAP, and handled at the router instead of the SMTP service (presumably to lower the cost or make DoS attacks more difficult).
There's a good way to test this: Configure Outlook, Mail.app, or some other mail client that knows how to connect to gmail, and uses SMTP to send mail via gmail. Run your script a few seconds after fetching mail in the mail client. If it works, that's the problem. And in that case, the fix is to do the same kind of connection and login (IMAP? web service?) that the mail client does.
Or, of course, you can use the sample code Google provides at the above links instead of working it out from first principles.
(Of course gmail also has to accept server-to-server SMTP connections, but they could easily have a different auth scheme for that. I'm assuming you're trying to do a client-to-server connection, rather than server-to-server.)
The other possibility is that you're on some kind of blacklist—e.g., gmail thinks your IP belongs to a spammer. This could also be dynamic—maybe anyone who makes a connection to port 587 but doesn't oauth properly gets blocked for the next N seconds. At any rate, this is also easy to test: Configure Outlook, Mail.app, etc. If this is the problem, they won't be able to send mail either.
There's a third possibility, that no one is allowed to connect to port 587, and Google wants you to use port 565 or 25 instead.
For easier debugging, you might want to consider writing an even simpler script that just creates a socket and connects, instead of using smtplib:
import socket
s = socket.socket()
s.connect(('smtp.gmail.com', 587))
Or, even more simply, just netcat from the command line:
nc smtp.gmail.com 587
To answer your side question:
Is there a work around to let python act as a regular browser?
That's not the issue. A regular browser doesn't make SMTP connections; it makes web service connections using Javascript code downloaded from gmail.com.
Of course Python can also make web services connections.
And it can act as much or as little like a "regular browser" (e.g., User-Agent, Referer, etc. headers) as you desire, but that probably isn't relevant—either the gmail web service API is public and has clear, published rules for how to authenticate yourself (in which case you just do what the rules say), or it's private and you shouldn't be trying to fool whatever protection they're using unless you want to get into an arms race.
At any rate, in this case, we know it's public, so we don't have to guess.

Categories

Resources