python:发送邮件,在带有"with"的邮件中失败.堵塞 [英] python: sending a mail, fails when inside a "with" block

查看:52
本文介绍了python:发送邮件,在带有"with"的邮件中失败.堵塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这段代码

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, composed)
test.close()

有效,但是写成这样

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

失败,并显示消息

Unable to send the email. Error:  <class 'AttributeError'>
Traceback (most recent call last):
  File "py_script.py", line 100, in <module>
    with smtplib.SMTP('smtp.gmail.com', 587) as s:
AttributeError: __exit__

为什么会这样?(树莓派上的python3)谢谢

Why is this happening? (python3 on a raspberry pi) Thx

推荐答案

您没有使用Python 3.3或更高版本.在您的Python版本中, smtplib.SMTP()不是上下文管理器,并且不能在 with 语句中使用.

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.

由于没有 __ exit __ 方法,这是上下文管理器的要求.

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

smptlib.SMTP()文档:

版本3.3中的更改:添加了对 with 语句的支持.

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

您可以使用 @将其包装在上下文管理器中contextlib.contextmanager :

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

from contextlib import contextmanager
from smtplib import SMTPResponseException, SMTPServerDisconnected

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

这使用与Python 3.3中添加的退出行为相同的行为.像这样使用它:

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

with quitting_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.

这篇关于python:发送邮件,在带有"with"的邮件中失败.堵塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆