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 !
Related
I want to send a E-mail using python using this code but the final result is a "Connection unexpectedly closed" error:
import smtplib
sender_email = "example#gmail.com"
rec_email = "example2#gmail.com"
password = "password"
message = "Test message using python !"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender_email, password)
server.sendmail(sender_email, rec_email, message)
This is the error:
raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed
It might be that the bigger email providers (I would believe this includes Gmail) block 'unsafe applications' from accessing the server.
You might want to try to login to sender_email and there should be an option somewhere that allows 'unsafe applications to access', or something similar.
I had a similar problem when doing the same thing with my Yahoo account, and this basically solved the problem.
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
Following is a simple python script to send emails using gmail smtp server. This code works from my localhost in my windows machine but when i run the same code from a remote linux server, "socket.error: [Errno 97] Address family not supported by protocol" is thrown and the exception happens at this line " server = smtplib.SMTP('smtp.gmail.com:587')". I appreciate any help on what is causing this error. Thanks!
fromaddr = ''
toaddrs = ''
# Credentials (if needed)
username = ''
password = ''
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
msg = MIMEText('This is a test message')
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()
This maybe a repeated question but I'm still facing issues on this, hope there's a solution around. Thanks in advance.
I'm trying to send mail through the company's server
I'm currently using Python version 2.6 and Ubuntu 10.04
This is the error message I got
Traceback (most recent call last):
File "hxmass-mail-edit.py", line 227, in <module>
server.starttls()
File "/usr/lib/python2.6/smtplib.py", line 611, in starttls
raise SMTPException("STARTTLS extension not supported by server.") smtplib.SMTPException: STARTTLS extension not supported by server.
Here goes part of the code
server = smtplib.SMTP('smtp.abc.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.ehlo()
server.login('sales#abc.com', 'abc123')
addressbook=sys.argv[1]
Remove the ehlo() before starttls().
starttls() + ehlo() results in two HELLO messages, which cause the server remove the STARTTLS in the reply message.
server = smtplib.SMTP('smtp.abc.com', 587)
server.starttls()
server.ehlo()
server.login('sales#abc.com', 'abc123')
I had a similar issue trying to send a mail through the company's server (without autentication needed)
I solved removing the server.ehlo and removing the port number:
server = smtplib.SMTP("smtp.mycompany.com")
server.sendmail(fromaddr, toaddr, text)
removing server.ehlo() before server.starttls() helped me get my code working! Thank you, Leonard!
my code:
s = smtplib.SMTP("smtp.gmail.com",587)
s.starttls()
s.ehlo
try:
s.login(gmail_user, gmail_psw)
except SMTPAuthenticationError:
print 'SMTPAuthenticationError'
s.sendmail(gmail_user, to, msg.as_string())
s.quit()
The error says it all, it seems the SMTP server sou are using doesn't support STARTTLS and you aru issuing server.starttls(). Try using the server without calling server.starttls().
Without more info is the only I can say.
I am able to resolve the issue with below code, by adding port number with server name:
server = smtplib.SMTP('smtp.abc.com:587')
from smtplib import SMTP_SSL, SMTP, SMTPAuthenticationError
from ssl import create_default_context
from email.message import EmailMessage
sender = 'aaa#bbb.com'
description = "This is the test description supposed to be in body of the email."
msg = EmailMessage()
msg.set_content(description)
msg['Subject'] = 'This is a test title'
msg['From'] = f"Python SMTP <{sender}>"
msg['To'] = 'bbb#ccc.com'
def using_ssl():
try:
server = SMTP_SSL(host='smtp.gmail.com', port=465, context=create_default_context())
server.login(sender, password)
server.send_message(msg=msg)
server.quit()
server.close()
except SMTPAuthenticationError:
print('Login Failed')
def using_tls():
try:
server = SMTP(host='smtp.gmail.com', port=587)
server.starttls(context=create_default_context())
server.ehlo()
server.login(sender, password)
server.send_message(msg=msg)
server.quit()
server.close()
except SMTPAuthenticationError:
print('Login Failed')
By testing and researching myself, I found out that the gmail servers do not use tls connections with python anymore.
You must not use service.startttls(). Gmail service do not support this type of connection anymore.
Also remember to use the SMTP ports (mail reserved ports) for sending emails.
POP3 and IMAP ports for receiving email.
s_u = "Test"
service = smtplib.SMTP_SSL("smtp.gmail.com", 465)
service.ehlo()
service.sendmail("SENDER_EMAIL","RECEIVER_EMAIL","MESSAGE")
You can't send the email even if you put the correct credentials,
look at this: Login credentials not working with Gmail SMTP
Are you sure that you want to encrypt (StartTLS) the connection to the mail server? I would contact someone who knows the insides of that server to see what protocol/encryption to use.
You say that upon removing the call to server.starttls(), you get a different series of error messages. Could you please post those messages as well?
Also, you might want to read up on StartTLS so you understand what it is and why you would want to use it. It seems you're writing a Serious Business program, in which case you'll probably want to understand what you are doing, security-wise.
Yes putting server.starttls() above server.ehlo() solved this.