user12209133
user12209133

Reputation:

Problem sending email with Google App Password in my function

I'm trying to create a function in Python that enables me to send an email from my email address to that of my intended recipient.

I have set up Google's 2-Step Verification with my Gmail and have set up a Google App Password.

So far, I have looked at examples online, but I don't know why send_email() is not working:

def send_email():
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo() 
    server.login('<my_email_address>', '<google_app_password>')

    subject = 'You've Got Mail!'
    body = 'How are you buddy?'

    message = f'Subject: {subject}\n\n{body}'

    server.sendmail(
        '<my_email_address>',
        '<my_intended_recidpients_email_address>',
        message
    )
    print('Email has been successfully sent')

    server.quit()

What could be the issue?

Upvotes: 0

Views: 168

Answers (1)

John Park
John Park

Reputation: 335

You're missing 2 lines of code.

After server.ehlo(), you need:

    server.starttls()
    server.ehlo()

server.starttls() is necessary since it tells an email server that an email client wants to turn an existing insecure connection into a secure one.

The second server.ehlo() after server.starttls() is needed because after completing the TLS handshake, the SMTP protocol is reset to its initial state.

Upvotes: 1

Related Questions