How to Send an Email With Gmail as Provider Using Python

How to send an email with Gmail as provider using Python?

You need to say EHLO before just running straight into STARTTLS:

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()

Also you should really create From:, To: and Subject: message headers, separated from the message body by a blank line and use CRLF as EOL markers.

E.g.

msg = "\r\n".join([
"From: user_me@gmail.com",
"To: user_you@gmail.com",
"Subject: Just a message",
"",
"Why, oh why"
])

Note:

In order for this to work you need to enable "Allow less secure apps" option in your gmail account configuration. Otherwise you will get a "critical security alert" when gmail detects that a non-Google apps is trying to login your account.

How to send an email using python after Google's policy update on not allowing just username and password?

Here is a more precise answer with all the main steps. I hope it will help other people.

  1. Log in into your email account: https://myaccount.google.com

  2. Then go to the security part

Sample Image

Be sure that you have turn on two steps verification and click on "App password"

Sample Image


  1. After select email and the corresponding device

Sample Image


  1. It will generate a password that will look like this; it is this password that you have to use in your python script.

Sample Image


  1. This password will appear here; in this place, you will have the option to erase it (so it will be no longer be useful to connect to your email account).

Sample Image

Hope it will help other people!

What's solution for sending emails from python while gmail the less secure apps is not enabled anymore

If you want to continue using Gmail SMTP, you can set it up by setting an app password. An app password works like an alternate password for your account. It can only be used by the applications you share it with, so it’s more secure than sharing your primary password.

Here's how you can set it up: https://support.google.com/accounts/answer/185833?hl=en

send email with Gmail Python

You must allow the "Less secure apps" in Google configurations.

Here is the link of another thread about it : Link



Related Topics



Leave a reply



Submit