How to Read emails from an specific mail only with the Gmail API

Question:

So I am a novice programmer that knows nearly nothing about how to create an API, and I’ve been trying to make a script with Python that allows me to read my last 10 mails from my Gmail Account, but now I wanna make it so it only reads mails from an specific Email and I don’t know how to do it

  service = build('gmail', 'v1', credentials=creds)

    #Get Mails
    results = service.users().messages().list(userId='me', labelIds=['INBOX']).execute()
    messages = results.get('messages', [])

    message_count = 10
    for message in messages[:message_count]:
        msg = service.users().messages().get(userId='me', id=message['id']).execute()
        email = (msg['snippet'])
        print(f'{email}n')

How I already said, I’m a novice programmer so don’t know how to approach this problem.

Asked By: Enanooo12

||

Answers:

Here’s an example of how to read emails from a specific email address using the Gmail API in Python:

from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build

def read_emails_from_specific_email(email_address, service):
    result = service.users().messages().list(userId='me', q=f'from:{email_address}').execute()
    messages = result.get('messages', [])
    for message in messages:
        msg = service.users().messages().get(userId='me', id=message['id']).execute()
        print(f'Subject: {msg["subject"]}')
        print(f'From: {msg["from"]}')
        print(f'Body: {msg["body"]}')

# Use a service account to access the Gmail API
creds = Credentials.from_service_account_file('path/to/service_account.json', scopes=['https://www.googleapis.com/auth/gmail.readonly'])
service = build('gmail', 'v1', credentials=creds)

# Read emails from a specific email address
read_emails_from_specific_email('[email protected]', service)

In this example, the read_emails_from_specific_email function takes two arguments: email_address and service. The service argument is an instance of the Gmail API client, which is used to interact with the API. The function uses the API to retrieve a list of messages that were sent from the specified email_address, and then loops through the messages to print their subject, sender, and body.

Before calling the function, the code uses a service account to obtain an authorization token, which is used to access the Gmail API. The service account credentials are stored in a JSON file, which is passed to the Credentials.from_service_account_file method. The scopes argument specifies the Gmail API scopes that the application needs to access.

Finally, the read_emails_from_specific_email function is called, passing the email address to search for and the service instance as arguments.

Answered By: Abrd
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.