Tech

Get the last 10 messages from Gmail using Python and Google API

Spread the love

I was trying to get the last 10 messages from my gmail inbox and I could not find anything online. Hence, I thought I would share with everyone. The 2 main method that obtain the 10 message is in ListMessagesMatchingQuery() and GetMessage():

 

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient import errors

import base64
import email
import string

try:
  import argparse
  flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
  flags = None

SCOPES = ‘https://www.googleapis.com/auth/gmail.readonly’
CLIENT_SECRET_FILE = ‘client_secrets.json’
APPLICATION_NAME = ‘Gmail API Python Quickstart’

def get_credentials():
  home_dir = os.path.expanduser(‘~’)
  credential_dir = os.path.join(home_dir, ‘.credentials’)
  if not os.path.exists(credential_dir):
    os.makedirs(credential_dir)
  credential_path = os.path.join(credential_dir,‘gmail-python-quickstart.json’)

  store = Storage(credential_path)
  credentials = store.get()
  if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
    flow.user_agent = APPLICATION_NAME
    if flags:
      credentials = tools.run_flow(flow, store, flags)
    else: # Needed only for compatibility with Python 2.6
      credentials = tools.run(flow, store)
    print(‘Storing credentials to ‘ + credential_path)
  return credentials

def getService():
  credentials = get_credentials()
  http = credentials.authorize(httplib2.Http())
  service = discovery.build(‘gmail’, ‘v1’, http=http)
  return service

def ListMessagesMatchingQuery(query=’category:primary is:unread’):
  try:
    service = getService()
    response = service.users().messages().list(userId=’me’,q=query).execute()
    messages = []
    v=0;
    results = “”;
    if ‘messages’ in response:
      messages.extend(response[‘messages’])
       for msg in messages:
         v = v+1;
         results = results + “, “+ GetMessage(msg[‘id’])
         if(v>10):
             break

    if(v==0):
      return “You do not have any unread emails.”
    else:
      return “You have unread emails from “+ results
  except errors.HttpError, error:
    print (error)

 

def GetMessage(msg_id):
  try:
    service = getService()
    message = service.users().messages().get(userId=’me’, id=msg_id).execute()
    details = message[‘payload’]
    test = details[‘headers’]
    results = “”;
    for i in range(len(test)):
      t = test[i]
       if(t[‘name’] == ‘From’):
         email_from = t[‘value’]
         email_from = string.replace(email_from, ‘”‘, ”)
         email_from = email_from[:email_from.find(‘<‘)]
         results = email_from;
         break
    return results
  except errors.HttpError, error:
    print (error)

 

ListMessagesMatchingQuery()


Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *