This time, I will explain the procedure to use Gmail API in Python. By the time I use the Gmail API, I often enable the API, create credentials, and install libraries, so I wrote it as a memorandum.
To use the Gmail API, you need to enable the API on Google Cloud Platform (GCP). Please access GCP from here (https://console.cloud.google.com/).
When you access for the first time, the following screen will appear, so agree to the terms of use and click "Agree and execute".
From "Select Project"
Click New Project.
You need to set the project name, so give it a descriptive name. After entering, click "Create".
The project is now created.
Next, we will enable the Gmail API. When you type "gmail" in the search window, Gmail API is displayed, so click it.
The project selection screen will appear, so click on the project you just created.
Click "Enable" in the Gmail API.
The Gmail API is now enabled.
Next, set up to get permission to use Gmail from users who use this program. If the program alone can send an email without permission from the user, it may be abused. Therefore, it is necessary to set to get permission from the user when the program is executed.
If the screen below appears, click "Create Credentials".
On the "Add Credentials to Project" screen, make the settings as shown below. Since we will be using the API from a Python script this time, we have selected "Other UI (Windows, CLI tools, etc.)" as the location to call the API. Also, I want to get the information of the user's received mail, so I selected "User data" as the type of data I want to access. After completing the settings, click "Required Credentials".
A dialog will appear. Click "Set consent screen".
"When you select the" OAuth consent screen "tab in the sidebar, the following screen will appear. Select" External "and click" Create ".
Set an appropriate name in "Application name" and save.
Once this is done, you will be returned to the authentication information creation screen.
Select the Credentials tab and click Create Credentials. Select "OAuth Client ID" from the displayed menu.
Select "Desktop App" in "Application Type" and give an appropriate name. Click "Create" when you can.
A dialog for completing the creation will be displayed, so click "OK".
After transitioning to the screen below, download the JSON file of the authentication information.
Let's install the library required to use the Gmail API with Python with pip. pip is a Python package management tool that allows you to easily load and use external libraries. Open a command prompt for Windows and a terminal for Mac and execute the following commands.
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Now you're ready to use the Gmail API.
I explained the procedure to use Gmail API in Python. If you use the Gmail API, you can automate the sending of emails, so please refer to it if you have work to send emails on a regular basis.
Recommended Posts