【问题标题】:AttributeError: SMTP_SSL instance has no attribute '__exit__'AttributeError:SMTP_SSL 实例没有属性“__exit__”
【发布时间】:2020-08-07 13:43:35
【问题描述】:

我知道还有其他类似的问题,但我遵循了答案,但我的代码仍然有同样的错误:

import csv, smtplib, ssl

message = """Subject: Test

Hi {name}"""
from_address = "random@gmail.com"
password = "pasword"



context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
    server.login(from_address, password)
    with open("contacts_file.txt") as file:
        reader = csv.reader(file)
        next(reader)
        next(reader) 
        for number, name, email in reader:
            server.sendmail(
                from_address, email, message.format(name=name)
            )
        server.quit()

谢谢!

【问题讨论】:

  • 你用的是什么版本的python? with 支持在 3.3 中添加到 smtplib

标签: python ssl server smtp attributeerror


【解决方案1】:

使用的 smtplib 版本不支持上下文管理器。您很可能正在使用低于 3.3 的 Python 版本。

为了理解错误,我创建了这两个类并将其与文本文件 hello.txt 一起保存。第一个类不支持上下文管理器,它会引发与您所拥有的类似的错误,而第二个则不会。


class OpenWithOutExit:

    '''
    This class has no special dunder for enter and exit used to create context manager
    '''

    def __init__(self, file, mode='r'):
        self.data = open(file, mode)

    def close(self):
        self.data.close()



class OpenWithExit:

    '''
    This class has special dunder for enter and exit used to create context manager
    '''

    def __init__(self, file, mode='r'):
        self.file = file
        self.mode = mode


    def __enter__(self):
        self.data = open(self.file, self.mode)
        return self.data

    def __exit__(self, exception_type, exception_value, traceback):

        self.data.close()
        print('We exist without issue')

if __name__ == '__main__':

    # using class context manager
    try:
        with OpenWithExit('hello.txt') as f:
                #do something
                pass

    except AttributeError as a:
        print('This will not print')

    # using a class without context manager

    try:
        with OpenWithOutExit('hello.txt') as f:
            # do something
            pass
    except AttributeError as e:
        print('This will cause Attribute exit error')

        raise e

【讨论】:

  • 非常感谢!我正在使用旧版本的 python 运行该文件。
猜你喜欢
  • 2015-08-30
  • 1970-01-01
  • 2015-12-29
  • 2015-01-19
  • 2016-06-29
  • 2012-10-07
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多