Reputation:
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
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