Python solved SMTP ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1002)

Usually, we send email by SMTP using:

def send_email(receivers, subject, body):
    msg = EmailMessage()
    msg['From'] = SMTP_USER
    msg['Bcc'] = receivers
    msg['Subject'] = subject
    msg.add_alternative(body, subtype='html')

    with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) as server:
        server.login(SMTP_USER, SMTP_PASS)
        return server.send_message(msg)

The SMTP_USER, SMTP_PASS, SMTP_HOST, SMTP_PASS are variables should be changed to your own.

This will work on Python 3.9 but we give following error:

ssl.SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:1002)

To solve it, we need add context for the connection.

def send_email(receivers, subject, body):
    msg = EmailMessage()
    msg['From'] = SMTP_USER
    msg['Bcc'] = receivers
    msg['Subject'] = subject
    msg.add_alternative(body, subtype='html')

    context = ssl.create_default_context()
    context.set_ciphers('DEFAULT@SECLEVEL=1')
    with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT, context=context) as server:
        server.login(SMTP_USER, SMTP_PASS)
        return server.send_message(msg)

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *