Skip to content Skip to sidebar Skip to footer

Python: Sending A Mail, Fails When Inside A "with" Block

I am wondering why this code test = smtplib.SMTP('smtp.gmail.com', 587) test.ehlo() test.starttls() test.ehlo() test.login('address','passw') test.sendmail(sender, recipients, comp

Solution 1:

You are not using Python 3.3 or up. In your version of Python, smtplib.SMTP() is not a context manager and cannot be using in a with statement.

The traceback is directly caused because there is no __exit__ method, a requirement for context managers.

From the smptlib.SMTP() documentation:

Changed in version 3.3: Support for the with statement was added.

You can wrap the object in a context manager with @contextlib.contextmanager:

from contextlib import contextmanager
from smtplib import SMTPResponseException, SMTPServerDisconnected

@contextmanagerdefquitting_smtp_cm(smtp):
    try:
        yield smtp
    finally:
        try:
            code, message = smtp.docmd("QUIT")
            if code != 221:
                raise SMTPResponseException(code, message)
        except SMTPServerDisconnected:
            passfinally:
            smtp.close()

This uses the same exit behaviour as was added in Python 3.3. Use it like this:

withquitting_smtp_cm(smtplib.SMTP('smtp.gmail.com', 587)) as s:
    s.ehlo()
    s.starttls()
    s.ehlo()
    s.login('address','passw')
    s.sendmail(sender, recipients, composed)

Note that it'll close the connection for you.

Post a Comment for "Python: Sending A Mail, Fails When Inside A "with" Block"