0

I am trying to send email (Gmail) using python, but I am getting following error:

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

My code:

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')

The following is the error:

/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

1 Answer 1

1

So, this may be based on how you're forming the SMTP messages. They broadcast in batch, kind of the way FTP, and HTTP does; but the following should help:

import smtplib
USR = #<[email protected]
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('[email protected]', '[email protected]', '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. Hope it helps

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Jesse for the solution, I have tried the same but it didn't resolve the issue. Still Encountering the mentioned Error ``` server.starttls() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/smtplib.py", line 772, in starttls context = ssl._create_stdlib_context(certfile=certfile, AttributeError: module 'ssl' has no attribute '_create_stdlib_context' ```
Did you make sure to run an ehlo before running the starttls?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.