I am attempting to create a script that send an email, using Gmail. However, my code freezes when the line below is ran:
smtplib.SMTP("smtp.gmail.com", 587)
It is before my username and password are entered, so it is nothing to do with my Gmail account. Why is this happening? I am using Python 3.6.3
The full code is below:
import smtplib
# Specifying the from and to addresses
fromaddr = 'XXX#gmail.com'
toaddrs = 'YYY#gmail.com'
# Writing the message (this message will appear in the email)
msg = 'Enter you message here'
# Gmail Login
username = 'XXX#gmail.com'
password = 'PPP'
# Sending the mail
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
It is most likely a firewall or similar issue. On the machine having the issue, try running this on the command line:
ping smtp.gmail.com
Assuming that works, then try:
telnet smtp.gmail.com 587
I'm assuming a Linux machine with this command. You'll need to adapt for others. If that connects, type ehlo list and the command should show some info. Type quit to exit.
If that doesn't work, then check your iptables.
sudo iptables -L
This will either show something like ACCEPT all under Chain INPUT or if not, you'll need to ensure that you are accepting established connections with something like:
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
The output chain is often open, but you should check that too.
If you are on AWS, check your security group isn't blocking outgoing connections.
If it's hanging in the call to smtplib.SMTP, and the server requires SSL, then most likely the issue is that you need to call smtplib.SMTP_SSL() (note the _SSL) instead of calling smtplib.SMTP() with a subsequent call to server.starttls() after the ehlo. See SMTPLib docs for SMTP_SSL for more details.
This fixed the issue for me.
Use server.ehlo() in your code.
Code Snippet:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
For authentication error:
http://joequery.me/guides/python-smtp-authenticationerror/
Add following code snippet and run again.
try:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.close()
print 'successfully sent the mail'
except:
print "failed to send mail"
You don't need the ehlo call. These days, you do need an app password with Gmail. And crucially, you need the right server address. I stupidly copied smtp.google.com from some bad instructions, and the call hung. Changing to smtp.gmail.com fixed it. Duh.
I've been using python for a bit now and have been using the email function without any errors in the past but on the latest program I have made I've been getting this error
Traceback (most recent call last):
File "daemon.py", line 62, in <module>
scraper.run()
File "c:\cfsresd\scraper.py", line 48, in run
self.scrape()
File "c:\cfsresd\scraper.py", line 44, in scrape
handler(msg)
File "daemon.py", line 57, in handler
server.ehlo()
File "C:\Python27\lib\smtplib.py", line 385, in ehlo
self.putcmd(self.ehlo_msg, name or self.local_hostname)
File "C:\Python27\lib\smtplib.py", line 318, in putcmd
self.send(str)
File "C:\Python27\lib\smtplib.py", line 310, in send
raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first
I used the same email code for all my projects but this is first time is done it. I've tried adding the connect() but that made no difference. Below is email section of my script
msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
msg['Subject'] = "msg.channel"
msg['From'] = ('removed')
msg['To'] = ('removed')
server.login('user','password')
server.sendmail(msg.get('From'),msg["To"],msg.as_string())
server.close()
server.ehlo()
server.quit()
print 'sent'
cheers for any help
shaggy
all sorted took a few idea and tried the code below
msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
server = smtplib.SMTP('smtp.gmail.com')
server.starttls()
server.login('user','pass')
msg['Subject'] = "msg.channel"
msg['From'] = ('from')
msg['To'] = ('to')
server.sendmail(msg.get('From'),msg["To"],msg.as_string())
server.quit()
So i removed ehlo(), close() and port number. now i have to workout how to change the subject to msg.channel so it changes each time.
thanks all
Try using SMTP's empty constructor, then call connect(host, port):
server = smtplib.SMTP()
server.connect('smtp.gmail.com', '587')
server.ehlo()
server.starttls()
server.login(username, password)
You have an ehlo after close. That seems unlikely to ever succeed. Also, quit does close so you can probably just get rid of the ehlo and close calls near the end
You can still have an encrypted connection with the smtp server by using the SMTP_SSL class without needing the starttls call (shorter). You don't need to be calling the ehlo every time, that's done automatically when needed, and when connecting to the default port, don't have to supply one when creating instances SMTP* classes.
msg = MIMEText ('%s - %s' % (msg.text, msg.channel))
msg['To'] = ','.join(receivers)
msg['Subject'] = 'msg.channel'
msg['From'] = 'someone#somedomain.com'
Using SMTP with the starttls:
server = smtplib.SMTP('smtp.gmail.com')
server.starttls()
server.login('user', 'password')
server.sendmail(msg['From'], receivers, msg.as_string())
and now with the SMTP_SSL class
server = smtplib.SMTP_SSL('smtp.gmail.com')
server.login('user', 'password')
server.sendmail(msg['From'], receivers, msg.as_string())
and finally
server.quit()
For Pyhton 3.6.*
Note : In gmail it will work only if 2-Step verification is turned off.
Allow gmail to open via low secured app.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from_addr = 'sender-email-id'
to_addr = 'receiver-email-id'
text = 'Hi Friend!!!'
username = 'sender-username'
password = 'password'
msg = MIMEMultipart()
msg['From'] = from_addr
msg['To'] = to_addr
msg['Subject'] = 'Test Mail'
msg.attach(MIMEText(text))
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(from_addr,to_addr,msg.as_string())
server.quit()
I'm the maintainer of yagmail, a package that should make it really easy to send an email.
import yagmail
yag = yagmail.SMTP('user','password')
yag.send(to = 'to#gmail.com', subject = 'msg.channel')
when yag leaves scope, it will auto-close.
I would also advise you to register in keyring once, so you'll never have to write the password in a script. Just run once:
yagmail.register('user', 'password')
You can then shorten it to this:
SMTP().send('to#gmail.com', 'msg.channel')
You can install it with pip or pip3 (for Python 3). You can also read more about it, with functionality as easily adding attachments, inline images/html, aliases etc.
I had a similar problem when I tried to send an e-mail from Celery (as a Docker container). I added env_file to the worker and beat containers in a docker compose file.
env_file: ./env/dev/.env
In that file I have an e-mail configuration.
EMAIL_HOST=smtp.gmail.com
EMAIL_HOST_USER=your_mail
EMAIL_HOST_PASSWORD=your_password
EMAIL_PORT=587
I solved this error just by removing this line:
server.quit()
raise SMTPServerDisconnected('please run connect() first')
if you had this error you my be want install this :
pip install django-smtp-ssl
this one to install smtp library and ssl protocol
its work perfecly for me
I'm writing a small python script to send an email, but my code isn't even getting past smtp connection. I'm using the following code, but I never see "Connected". Additionally, I'm not seeing an exception thrown, so I think it's hanging on something.
import os
import platform
import smtplib
#Define our SMTP server. We use gmail. Try to connect.
try:
server = smtplib.SMTP()
print "Defined server"
server.connect("smtp.gmail.com",465)
print "Connected"
server.ehlo()
server.starttls()
server.ehlo()
print "Complete Initiation"
except Exception, R:
print R
Port 465 is for SMTPS; to connect to SMTPS you need to use the SMTP_SSL; however SMTPS is deprecated, and you should be using 587 (with starttls). (Also see this answer about SMTPS and MSA).
Either of these will work: 587 with starttls:
server = smtplib.SMTP()
print("Defined server")
server.connect("smtp.gmail.com",587)
print("Connected")
server.ehlo()
server.starttls()
server.ehlo()
or 465 with SMTP_SSL.
server = smtplib.SMTP_SSL()
print("Defined server")
server.connect("smtp.gmail.com", 465)
print("Connected")
server.ehlo()
I am trying to learn about how to send emails using Python. Using scripts from Tutorial's Point, and Stack Overflow I have created a basic script which can send emails using Gmail. I have a few questions about several lines of code. They appear to be communicating with the Gmail Server.
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
What does server.ehlo mean? Is it specific to gmail?
server.starttls()
What does this mean?
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
What is server.quit()?
ehlo is part of the protocol exchange between the client side and server side
ehlo gives the name of the client side to the server
starttls starts up the encryption and authentication for the SSL socket layer
login sends credentials as described in the SMTP spec
sendmail does the other SMTP protocol commands, mail from, rcpt to and data
quit sends a command to close the connection from the server end
I want to make use of SMTP. I have written a simple code that will
send mail from one mail address to another.
import smtplib
msg = "smtp_mail"
server = smtplib.SMTP('MailServerAddress')
server = smtplib.SMTP(server)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
here I am getting an error AttributeError: SMTP instance has no attribute
'find'
Please help!!
Your program crashes on line : server = smtplib.SMTP(server)
Just remove this line, it's twice !