I am trying to send email (Gmail) using python, but I am getting following error:
'AttributeError: module 'ssl' has no attribute '_create_stdlib_context'
My code:
def send_email(self):
username = '****#gmail.com'
password = '****'
sent_to = '****#gmail.com'
msg = "Subject: this is the trail subject..."
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server.login(username, password)
server.sendmail(username, sent_to, msg)
server.quit()
print('Mail Sent')
The following is the error:
/usr/local/bin/python3.8 /Users/qa/Documents/Python/python-api-testing/tests/send_report.py
Traceback (most recent call last):
File "/Users/qa/Documents/Python/python-api-testing/tests/send_report.py", line 23, in <module>
email_obj.send_email()
File "/Users/qa/Documents/Python/python-api-testing/tests/send_report.py", line 11, in send_email
server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 1031, in __init__
context = ssl._create_stdlib_context(certfile=certfile,
AttributeError: module 'ssl' has no attribute '_create_stdlib_context'
Start of /Users/qa/Documents/Python/python-api-testing/tests/send_report.py
So, this may be based on how you're forming the SMTP messages. They broadcast in batch, kind of the way FTP, and HTTP does; but the following should help:
import smtplib
USR = #<username#domain.tld
PWD = #<Password>
def sendMail(sender, receiver, message):
global USR, PWD
msg = '\r\n'.join([
f'From: {sender}',
f'To: {receiver}',
'',
f'{message}',
])
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(USR, PWD)
server.sendmail(msg)
server.quit()
if __name__ == "__main__":
sendMail('sender#dom.tld', 'receiver#dom.tld', 'This is a test, of the non-emergency boredom system.')
Python3 Docs indicate some error handling to be aware of, but the original idea I based this code around can be found here. Hope it helps
Related
here is the code from my college, but I thougt it's not much effecient 'cause it'll connect smtp server and login every time, and just send one mail..., so how about I connect smtp and login for the first time once the service started, and using this long connection to send mail aferwards?
def send_email(receiver, subject, mail_body):
msg = MIMEText(mail_body, _subtype='html', _charset='utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = XXXX#xx.com
msg['To'] = receiver
try:
smtp = smtplib.SMTP()
smtp.connect(xxxx.com)
smtp.login(user, password)
smtp.sendmail(XXXX#xx.com, receiver.split(','), msg.as_string())
except Exception:
logger.error('Send email failed: %s' % traceback.format_exc())
finally:
smtp.quit()
It's OK to reuse the connection to send email, but the server may terminate the connection at any time, that depends on server's strategy. So just catch the corresponding error and reconnect again.
def send_email(receiver, subject, mail_body):
try:
smtp = smtplib.SMTP()
smtp.connect(xxxx.com)
smtp.login(user, password)
# for test
for i in range (10):
smtp.sendmail(XXXX#xx.com, receiver.split(','), msg.as_string())
except Exception:
logger.error('Send email failed: %s' % traceback.format_exc())
finally:
smtp.quit()
using the above code, I test sending 10 emails using the same connection, but got Exception below, I think that may be related to the safety strategy of target smtp server.
[2021-03-01 15:56:25,386] [ERROR] [125:MainThread] [send_email.py:47] [send_email]:send email failed: Traceback (most recent call last):
File "send_email.py", line 41, in send_email
smtp.sendmail(EmailAccount, email_receiver.split(','), msg.as_string())
File "/usr/lib/python2.7/smtplib.py", line 737, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
SMTPSenderRefused: (450, 'Requested mail action not taken: too much delivery in this connection', 'xxxx#xxxx.com')
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 trying to send email with python but I'm getting SSL error and I don't know why.
File "./test.py", line 735, in <module>
mail() File "./test.py", line 721, in mail
server.starttls() File "/usr/local/lib/python2.7/smtplib.py", line 641, in starttls
raise RuntimeError("No SSL support included in this Python") RuntimeError: No SSL support included in this Python
How do I add SSL support?
its just a small function to test if i can send email with python
def mail():
import smtplib
global log_location
#inFile_list = open(log_location, 'r')
#msg = inFile_list.readlines()
#inFile_list.close()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
#Next, log in to the server
server.login("my username", "my password")
#Send the mail
msg = "\nHello!" # The /n separates the message from the headers
server.sendmail("mymail#gmail.com", "mymail#gmail.com", msg)
server.quit()
Tried to install _ssl.so manual but it didn't work.
instead I've upgraded from 2.7.6 to 2.7.7 and now i can import SSL.
import smtplib
import config
def send_email(subject,msg):
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(config.EMAIL_ADDRESS, config.PASSWORD)
message = 'subject: {}\n\n{}'.format(subject,msg)
server.sendmail(config.EMAIL_ADDRESS,config.EMAIL_ADDRESS, message)
server.quit()
print('all good')
except:
print('email failed to send')
subject = "TEST SUBJECT"
msg = "hello"
send_email(subject,msg)
This works for me but you must create a new file called config.py then put in
EMAIL_ADDRESS = "email"
PASSWORD = "pwd"
The last step is go to this link >>> https://myaccount.google.com/lesssecureapps<<< and turn it on. Now you can run the script
I am trying to send an email in Python:
import smtplib
fromaddr = '......................'
toaddrs = '......................'
msg = 'Spam email Test'
username = '.......'
password = '.......'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
I understand that this is probably not the correct message format.
Anyways, I get an error:
C:\.....>python email.py
Traceback (most recent call last):
File "email.py", line 1, in <module>
import smtplib
File "C:\.....\Python\lib\smtplib.py", line 47,
in <module>
import email.utils
File "C:\.....\email.py", line 15, in
<module>
server = smtplib.SMTP('smtp.gmail.com', 587)
AttributeError: 'module' object has no attribute 'SMTP'
I don't quite understand what I am doing wrong here... Anything incorrect?
NOTE: All the periods are replacements for password/email/file paths/etc.
Python already has an email module. Your script's name is email.py, which is preventing smtplib from importing the built-in email module.
Rename your script to something other than email.py and the problem will go away.
import smtplib
conn = smtplib.SMTP('imap.gmail.com',587)
conn.ehlo()
conn.starttls()
conn.login('youremail#gmail.com', 'your_password')
conn.sendmail('from#gmail.com','to#gmail.com','Subject: What you like? \n\n Reply Reply Reply')
conn.quit()
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 !