What is the recommended way of sending emails with gmail and python?
There are a lot of SO threads, but most are old and also smtp with username & password is not working any more or the user has to downgrade the security of their gmail (for example see here).
Is OAuth the recommended way?
For jupyter-notebook users, after following @apadana's instructions, if you get cryptic error messages, make sure you copy the code out into it's own python file and run it using
(still no clue how I figured that one out)
when you finish doing that, you're now almost in the clear.
make the last change: Gmail API Error from Code Sample - a bytes-like object is required, not 'str'
replace
with:
now, it should™ work.
final notes: remember there are two instances of the base64 encode thingie...
use
in method CreateMessageHtml
and
in method createMessageWithAttachment
the reason you gotta do this is because the message has the variable name 'msg' in CreateMessageHtml, but name 'message' in createMessageWithAttachment. Because reasons. That's why.
Here is the Python 3.6 code (and explanations) needed to send an email without (or with) an attachment.
(To send with attachment just uncomment the 2 lines bellow
## without attachment
and comment the 2 lines bellow## with attachment
)All the credit (and up-vote) to apadana
The answer shows how to send email with gmail API and python. Also updated the answer to send emails with attachment.
Gmail API & OAuth -> no need to save the username and password in the script.
The first time the script opens a browser to authorize the script and will store credentials locally (it will not store username and password). Consequent runs won't need the browser and can send emails straight.
With this method you will not get errors like SMTPException below and there is no need to allow Access for less secure apps:
Here are the steps to send email using gmail API:
(Wizard link here, More info here)
Step 2: Install the Google Client Library
Step 3: Use the following script to send email(just change the variables in main function)
Tip for running this code on linux, with no browser:
If your linux environment has no browser to complete the first time authorization process, you can run the code once on your laptop (mac or windows) and then copy the credentials to the destination linux machine. Credentials are normally stored in the following destination:
I modified this as follows to work with Python3, inspired by Python Gmail API 'not JSON serializable'
thanks, @Guillame, @apadana. @Guillaume's answer worked great for me in Win/Python3.7, but with one change. For the all the 3 print statements, I had to remove the "f", as in change:
to
Also look at the first part of @apandana's answer to get your client_secret.json file. That was more clearer for me.