【问题标题】:Python AttributeError: module 'ssl' has no attribute '_create_stdlib_context'Python AttributeError:模块'ssl'没有属性'_create_stdlib_context'
【发布时间】:2020-10-18 10:22:45
【问题描述】:

我正在尝试使用 python 发送电子邮件 (Gmail),但出现以下错误:

'AttributeError: 模块'ssl'没有属性'_create_stdlib_context'

我的代码:

def send_email(self):
    username = '****@gmail.com'
    password = '****'
    sent_to = '****@gmail.com'

    msg = "Subject: this is the trail subject..."
    server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    server.login(username, password)
    server.sendmail(username, sent_to, msg)
    server.quit()
    print('Mail Sent')

以下是错误:

/usr/local/bin/python3.8 /Users/qa/Documents/Python/python-api-testing/tests/send_report.py
Traceback (most recent call last):
  File "/Users/qa/Documents/Python/python-api-testing/tests/send_report.py", line 23, in <module>
    email_obj.send_email()
  File "/Users/qa/Documents/Python/python-api-testing/tests/send_report.py", line 11, in send_email
    server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 1031, in __init__
    context = ssl._create_stdlib_context(certfile=certfile,
AttributeError: module 'ssl' has no attribute '_create_stdlib_context'
Start of /Users/qa/Documents/Python/python-api-testing/tests/send_report.py

【问题讨论】:

    标签: python email smtp gmail smtplib


    【解决方案1】:

    因此,这可能取决于您如何形成 SMTP 消息。它们批量广播,就像 FTP 和 HTTP 一样;但以下应该会有所帮助:

    import smtplib
    USR = #<username@domain.tld
    PWD = #<Password>
    
    
    def sendMail(sender, receiver, message):
        global USR, PWD
    
        msg = '\r\n'.join([
            f'From: {sender}',
            f'To: {receiver}',
            '',
            f'{message}',
        ])
    
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(USR, PWD)
        server.sendmail(msg)
        server.quit()
    
    
    if __name__ == "__main__":
        sendMail('sender@dom.tld', 'receiver@dom.tld', 'This is a test, of the non-emergency boredom system.')
    

    Python3 Docs 表示需要注意一些错误处理,但我基于此代码的原始想法可以在here 找到。希望对你有帮助

    【讨论】:

    • 感谢@Jesse 的解决方案,我也尝试过,但没有解决问题。在 starttls context = ssl._create_stdlib_context( certfile=certfile, AttributeError: module 'ssl' has no attribute '_create_stdlib_context' ```
    • 您确定在运行starttls 之前运行ehlo 吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-28
    • 2023-04-06
    • 2018-06-16
    • 2015-03-09
    • 2016-12-26
    • 2016-04-10
    • 2017-04-07
    • 2013-07-05
    相关资源
    最近更新 更多