Google gmail api python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Gmail API requests in Python

License

corerd/GmailPythonAPI

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Gmail API requests in Python

gmailapi.py is a client front-end library script to make requests to the Gmail Google API.

Gmail API relies upon OAuth 2.0 protocol for authentication and authorization.

The description of the OAuth 2.0 authorization scenarios that Google supports can be found in Using OAuth 2.0 to Access Google APIs.

Making requests to the Gmail API

First, you’ll need a Google account with Gmail enabled.

To enable Gmail API you have to create a new Cloud Platform project in Google Cloud Console and enable the Gmail API in Google API Console.

Then gmailapi.py script requests an OAuth 2.0 access token from the Google Authorization Server, extracts a token from the response, and sends the token to the Gmail API that you want to access.

Here are the steps required to allow the script to send Gmail API requests.

1. Obtain OAuth 2.0 credentials from the Google Cloud Console

This step is required only once to turn on the Gmail API obtaining the OAuth 2.0 credentials (that is client ID and client secret) that are known to both Google and you.

Google has speeded up this process providing the Enable the Gmail API wizard that you can find in the Gmail Python Quickstart tutorial.

Читайте также:  Чем удалить ненужные css

The wizard creates a new Cloud Platform project named Quickstart with quickstart-random-number as ID, and automatically enables the Gmail API.

The project can be later renamed in your Google Cloud Console, while the project ID can no more be changed.

After the wizard has finished, you’ll find the credentials.json file saving your client configuration including client ID and client secret.

The client configuration of your project can be also downloaded any time from the Google API Console.

2. Install the Google Client Library

pip install -r requirements.txt 

3. Obtain OAuth 2.0 tokens from the Google Authorization Server

Before the gmailapi.py script performs its first Gmail API request, it must obtain a set of OAuth 2.0 tokens, that is:

  • an access token that grants limited lifetime access to the API;
  • a refresh token allowing the script to obtain new access tokens.

The script opens your default browser and submits to Google Authorization Server your OAuth 2.0 credentials saved in the credentials.json file.

After logging in with your Google account, an OAuth consent screen is presented to you asking to grant the requested permissions. If you’ll accept, the script will store the received OAuth 2.0 tokens (not username and password) in the token.pickle file.

Subsequent runs of the gmailapi.py script won’t need the browser and can send API request straight by means the access token that has limited lifetime. If the script needs access to a Gmail API beyond the lifetime of its access token, it will proceed automatically requesting a new one from the Google Authorization Server by means of the refresh token.

The OAuth consent screen that is presented to the you may show the warning This app isn’t verified if it is requesting scopes that provide access to sensitive user data. These applications must eventually go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to (unsafe).

The gmailapi.py library script

It is required the credentials.json file with your client ID and client secret from Google Cloud Console.

The script exports the following functions:

  • GetAuthTokens to obtain OAuth 2.0 tokens from Google Authorization Server;
  • gmSend to send an unicode email message from the user’s account with optional attachment.

Before any Gmail API request, the script checks out the OAuth 2.0 tokens and, if necessary, automatically obtains or refreshes them from Google Authorization Server.

The command-line application

Run the gmailapi.py script as a standalone application to checkout OAuth 2.0 tokens from Google Authorization Server.

Open a command-line window and run:

The script searches for the token.pickle file to read the access token and, if it is expired, a new one will be requested and saved to the same file without any further user interaction.

Читайте также:  Java with gradle это

If no valid OAuth 2.0 tokens are found, the script searches for the credentials.json file and, if found, will start the user consent process to obtain a new set of tokens, storing them to the token.pickle file.

Supported Python Versions

Python 2,7 and 3.6 are fully supported and tested. The gmailapi.py script may work on other versions of 3 though not tested.

You can find the gmsend_test.py command-line script that demonstrates how to use the gmailapi.py library to send a test message to someone with an optional attachment.

gmsend_test.py [attached-file-path] 

Example: to send a test message to someone attaching the gmail-logo.png file, open a command-line window and run:

python gmsend_test.py gmail-logo.png 

The gmailapi.py script doesn’t save any username and password, but it reads and writes the credentials.json and token.pickle files that contain your personal Google account data.

Please, keep these files in a secure private location and don’t put their content in any public sharing service such as GitHub.

Copyright (c) 2019 Corrado Ubezio

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at Apache Software Foundation.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

About

Gmail API requests in Python

Источник

How to read Emails from Gmail using Gmail API in Python ?

In this article, we will see how to read Emails from your Gmail using Gmail API in Python. Gmail API is a RESTful API that allows users to interact with your Gmail account and use its features with a Python script.

So, let’s go ahead and write a simple Python script to read emails.

Requirements

  • Python (2.6 or higher)
  • A Google account with Gmail enabled
  • Beautiful Soup library
  • Google API client and Google OAuth libraries

Installation

Install the required libraries by running these commands:

pip install –upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

Run this to install Beautiful Soup:

Now, you have to set up your Google Cloud console to interact with the Gmail API. So, follow these steps:

Go to Enable APIs and Services

  • Now, configure the Consent screen by clicking on OAuth Consent Screen if it is not already configured.

Create an OAuth Client ID

  • Choose application type as Desktop Application.
  • Enter the Application name, and click on the Create button.
  • The Client ID will be created. Download it to your computer and save it as credentials.json
Читайте также:  Php печать массива print

Please keep your Client ID and Client Secrets confidential.

Now, everything is set up, and we are ready to write the code. So, let’s go.

Code

The file ‘token.pickle‘ contains the User’s access token, so, first, we will check if it exists or not. If it does not exist or is invalid, our program will open up the browser and ask for access to the User’s Gmail and save it for next time. If it exists, we will check if the token needs to be refreshed and refresh if needed.

Now, we will connect to the Gmail API with the access token. Once connected, we will request a list of messages. This will return a list of IDs of the last 100 emails (default value) for that Gmail account. We can ask for any number of Emails by passing an optional argument ‘maxResults‘.

The output of this request is a dictionary in which the value of the key ‘messages‘ is a list of dictionaries. Each dictionary contains the ID of an Email and the Thread ID.

Now, We will go through all of these dictionaries and request the Email’s content through their IDs.

This again returns a dictionary in which the key ‘payload‘ contains the main content of Email in form of Dictionary.

This dictionary contains ‘headers‘, ‘parts‘, ‘filename‘ etc. So, we can now easily find headers such as sender, subject, etc. from here. The key ‘parts‘ which is a list of dictionaries contains all the parts of the Email’s body such as text, HTML, Attached file details, etc. So, we can get the body of the Email from here. It is generally in the first element of the list.

The body is encoded in Base 64 encoding. So, we have to convert it to a readable format. After decoding it, the obtained text is in ‘lxml‘. So, we will parse it using the BeautifulSoup library and convert it to text format.

At last, we will print the Subject, Sender, and Email.

Источник

Google gmail api python

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью