No attribute 'SMTP', error when trying to send email in Python - python

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()

Related

Python AttributeError: module 'ssl' has no attribute '_create_stdlib_context'

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

Connection Error SMTP python

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

sending email with python SSL error

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

Issue sending email with python?

I'm trying to make an email script in python. Here's what I have (from pythonlibrary.org):
#! /usr/bin/env python
import smtplib
import string
SUBJECT = "An email!"
TO = "me#icloud.com"
FROM = "me#gmail.com"
text = "This text is the contents of an email!"
BODY = string.join((
"From: %s" % FROM,
"To: %s" % TO,
"Subject: %s" % SUBJECT ,
"",
text
), "\r\n")
server = smtplib.SMTP('smtp.gmail.com')
server.login('me#gmail.com', 'mypassword') # Not very secure, I know, but this email is dedicated to this script
server.sendmail(FROM, [TO], BODY)
server.quit()
I get smtplib.SMTPException: SMTP AUTH extension not supported by server. Is this is so, then why does smtp.gmail.com respond at all? Is this a problem with Gmail, or my script, or something else?
Error message:
Traceback (most recent call last):
File "/Users/student/Desktop/mail.py", line 18, in <module>
server.login('*******#gmail.com', '**************')
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/smtplib.py", line 552, in login
smtplib.SMTPException: SMTP AUTH extension not supported by server.
You need to contact the gmail mail server on the submission port (587), not the default 25:
server = smtplib.SMTP('smtp.gmail.com', 587)
You also need to use server.starttls() before logging in (so that your password is not sent in the clear!). This is from a script I have and it works for me:
server = smtplib.SMTP()
server.connect("smtp.gmail.com", "submission")
server.starttls()
server.ehlo()
server.login(user, password)
Here's how to send e-mail using gmail in Python:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
login, password = 'user#gmail.com', getpass('Gmail password:')
# create message
msg = MIMEText('message body…', _charset='utf-8')
msg['Subject'] = Header('subject…', 'utf-8')
msg['From'] = login
msg['To'] = login
# send it via gmail
s = SMTP_SSL('smtp.gmail.com', 465, timeout=10)
s.set_debuglevel(1)
try:
s.login(login, password)
s.sendmail(msg['From'], msg['To'], msg.as_string())
finally:
s.quit()
I found I had to do an ehlo() and a starttls() before sending mail via gmail:
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
server.login(SERVER_EMAIL,EMAIL_HOST_PASSWORD)
It shouldn't make a difference with the login, but I use a MIMEMultipart from email.mime.multipart for the body, with something like:
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = mFrom
msg['To'] = mTo
if textBody:
part1 = MIMEText(textBody, 'plain')
msg.attach(part1)
if htmlBody:
part2 = MIMEText(htmlBody, 'html')
msg.attach(part2)
BODY = msg.as_string()

Python sendmail error script

#!/usr/bin/python
import smtplib
sender = 'from#fromdomain.com'
receivers = ['to#todomain.com']
message = """From: From Person <from#fromdomain.com>
To: To Person <TEST#yahoo.com>
Subject: SMTP e-mail test
This is a test e-mail message.
"""
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except SMTPException:
print "Error: unable to send email"
I keep getting the folllowing errors even though I imported everything. I'm using Linux, what's missing?
File "email.py", line 3, in <module>
import smtplib
File "/usr/lib/python2.7/smtplib.py", line 46, in <module>
import email.utils
File "/home/email.py", line 19, in <module>
except SMTPException:
The only obvious thing that should not work is that SMTPException needs to be smtplib.SMTPException (or import it for unqualified use with from smtplib import SMTPException).
Otherwise, after changing to my own (valid) addresses and my own SMTP server, your code works fine.

Categories

Resources