from __future__ import print_function import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from apiclient import discovery import httplib2 import os,sys import base64 #from bs4 import BeautifulSoup from collections import OrderedDict # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/gmail.modify'] def main(): pathJson = "C:\\Users\\chris\\OneDrive\\Documentos\\GitHub\\MOBEES-BR\\Backend\\dsp\\adm\\auth\\credentials_mail.json" pathPickle = "C:\\Users\\chris\\OneDrive\\Documentos\\GitHub\\MOBEES-BR\\Backend\\dsp\\adm\\auth\\token_mail.pickle" creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(pathPickle): with open(pathPickle, 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( pathJson, SCOPES) creds = flow.run_local_server(port=0) with open(pathPickle, 'wb') as token: pickle.dump(creds, token) service = build('gmail', 'v1', credentials=creds) # request a list of all the messages result = service.users().messages().list(userId='me',q='from:mailer-daemon subject:Failure').execute() # We can also pass maxResults to get any number of emails. Like this: #result = service.users().messages().list(maxResults=10, userId='me', q='from:mailer-daemon subject:Failure').execute() messages = result.get('messages') # messages is a list of dictionaries where each dictionary contains a message id. email_dest = [] for msg in messages: # Get the message from its id txt = service.users().messages().get(userId='me', id=msg['id']).execute() # Use try-except to avoid any Errors try: # Get value of 'payload' from dictionary 'txt' payload = txt['payload'] headers = payload['headers'] # Look for Subject and Sender Email in the headers for d in headers: if d['name'] == 'X-Failed-Recipients': email_dest.append(d['value']) break # The Body of the message is in Encrypted format. So, we have to decode it. # Get the data and decode it with base 64 decoder. #parts = payload.get('parts')[0] #parts = parts['parts'][0] #data = parts['parts'][0]['body']['data'] #data = data.replace("-","+").replace("_","/") #decoded_data = base64.b64decode(data) # Now, the data obtained is in lxml. So, we will parse # it with BeautifulSoup library #soup = BeautifulSoup(decoded_data , "lxml") #body = soup.body() # Printing the subject, sender's email and message #print("Subject: ", subject) #print("From: ", sender) #print("Message: ", body) #print('\n') except BaseException as error: try: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("ERRO: %s | %s | %s | %s" % (error, exc_type, fname, exc_tb.tb_lineno)) pass except: pass print("Email Dest: ",list(OrderedDict.fromkeys(email_dest))) if __name__ == '__main__': main()