Python get gmail emails

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.

This is a documentation of how to access gmail inbox with python using app key (new method).

License

medsagou/Read-email-from-gmail-inbox-using-python

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

How to access Gmail inbox through python — Mohamed Sagou

This tutorial will show you how to connect, access and read Gmail inbox with python. You need to have python 3 and PIP installed in your pc.

How to get user name and passowrd for connection

The username you will need for this connection is just the gmail username of the inbox that you want to read. example :

This is the important section of this hole process. The password that your python code will be use is actually a appkey generated by gmail it self.
First You need to login on your Gmail account, click on your profile picture on top right then go to «Manage your Google Account».

After that go to Security -> Scroll to «Signing in to Google», make sure that 2-step verification is on.

If so, then go to «App passwords», you may have to login again. Next, select the following fields, you may change the second field if your platform is different. Then click GENERATE button.

After generating the app password, you will have something similar to the folowwing screenshot (In my case it’s a fake password). Store the password that is provided in the following part, the you will be ready to the next step.

Require python code to read gmail inbox

Import «email» and «imaplib» modules.

import email import imaplib

Store our «username» (Gmail username) and app password in a variables.

user = "example@gmail.com" gmail_pass = "aaaaffffvvvvtttt" host = "imap.gmail.com"

Define the function with the parameters to decide how many emails to show, and if to contain the body of the email or not, both with defaults.

def read_email_from_gmail(count=3, contain_body = False):
mail = imaplib.IMAP4_SSL(host) mail.login(user, gmail_pass)

Using SELECT to chose the e-mails.

res, messages = mail.select('INBOX')

Caluclating the total number of sent Emails

Iterating over the sent emails

for i in range(messages, messages - count, -1): # RFC822 protocol res, msg = mail.fetch(str(i), "(RFC822)") for response in msg: if isinstance(response, tuple): msg = email.message_from_bytes(response[1]) # Store the senders email sender = msg["From"] # Store subject of the email subject = msg["Subject"] # Store Body body = "" temp = msg if temp.is_multipart(): for part in temp.walk(): ctype = part.get_content_type() cdispo = str(part.get('Content-Disposition')) # skip text/plain type if ctype == 'text/plain' and 'attachment' not in cdispo: body = part.get_payload(decode=True) # decode break else: body = temp.get_payload(decode=True) # Print Sender, Subject, Body print("-"*50) # To divide the messages print("From : ", sender) print("Subject : ", subject) if(contain_body): print("Body : ", body.decode())
read_email_from_gmail(3, True)
import email import imaplib user = "example@gmail.com" gmail_pass = "aaaaffffvvvvtttt" host = "imap.gmail.com" def read_email_from_gmail(count=3, contain_body=False): # Create server and login mail = imaplib.IMAP4_SSL(host) mail.login(user, gmail_pass) # Using SELECT to chose the e-mails. res, messages = mail.select('INBOX') # Caluclating the total number of sent Emails messages = int(messages[0]) # Iterating over the sent emails for i in range(messages, messages - count, -1): # RFC822 protocol res, msg = mail.fetch(str(i), "(RFC822)") for response in msg: if isinstance(response, tuple): msg = email.message_from_bytes(response[1]) # Store the senders email sender = msg["From"] # Store subject of the email subject = msg["Subject"] # Store Body body = "" temp = msg if temp.is_multipart(): for part in temp.walk(): ctype = part.get_content_type() cdispo = str(part.get('Content-Disposition')) # skip text/plain type if ctype == 'text/plain' and 'attachment' not in cdispo: body = part.get_payload(decode=True) # decode break else: body = temp.get_payload(decode=True) # Print Sender, Subject, Body print("-"*50) # To divide the messages print("From : ", sender) print("Subject : ", subject) if(contain_body): print("Body : ", body.decode()) # Close the connection. mail.close() mail.logout() # Call the function. read_email_from_gmail(3, True)

You Will find the .py file included in this repository as well.

  • Originale repository — Read-email-from-gmail-inbox-using-python
  • Website — github.com/medsagou
  • Frontend Mentor — @medsagou
  • Twitter — @sagoumohamed
  • stackoverflow — @medsagou
  • Linkedin — Mohamed Sagou

Источник

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

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.

Источник

Читайте также:  Java ожидание завершения всех потоков
Оцените статью