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

Sahil Sangani picture Sahil Sangani · Dec 27, 2018 · Viewed 7.9k times · Source

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 = "[email protected]"  # type: str # Enter your address
receiver_email = "[email protected]"  # 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)

Answer

snakecharmerb picture snakecharmerb · Dec 27, 2018

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