How to solve AttributeError: SMTP_SSL instance has no attribute '__exit__' in Python?

Viewed 10749

Could anyone help me to solve this error: AttributeError: SMTP_SSL instance has no attribute 'exit'.

I am working on a small module which sends multiple emails using Python. Python Version: 2.7.15 OS: MacOS X

import smtplib
import ssl
port = 465  # For SSL
smtp_server = "smtp.gmail.com"
sender_email = "abc@gmail.com"  # type: str # Enter your address
receiver_email = "xyz@gmail.com"  # Enter receiver address
password = 'xyz@0101'
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context ) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, message, receiver_email)
4 Answers

Support for using with statements with smtplib.SMTP_SSL was added in Python3.3, so it won't work in Python2.7

Something like this should work:

context = ssl.create_default_context()
server = smtplib.SMTP_SSL(smtp_server, port, context )
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message)
server.quit()

sorry for the error you encountered.

the reason you had those error is because the version of python you running on your machine is different from the version of python the code is written in

you are running python2 mean while the code is python

here are a few changes you can make

  1. change every occurrence of server to mailServer ( take note of capitalisation)

  2. Change smtp_server to smtpServer ( take note of capitalisation)

  3. the line with the with statement, remove the "with" and the "as" keywords. rewrite as follows

mailServer = smtplib.SMTP_SSL(smtpServer, port)

For me it worked when I typed python3 in front. For example: python3 /home/pi/yourscript.py

remove the context from server definition, it will work with python 2.7

context=ssl.create_default_context() server=smtplib.SMTP_SSL(smtp_server,port) server.login(sender,password) print('it worked!') server.sendmail(sender,reciever,message) print('Mail sent') server.quit()

Related