Python AttributeError: module 'ssl' has no attribute '_create_stdlib_context'

Python AttributeError: module 'ssl' has no attribute '_create_stdlib_context'

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

'AttributeError: module 'ssl' has no attribute '_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

因此,这可能取决于您构建 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 indicate some error handling to be aware of, but the original idea I based this code around can be found here。希望对你有帮助