processaAuthApiMail.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. from __future__ import print_function
  2. import pickle
  3. import os.path
  4. from googleapiclient.discovery import build
  5. from google_auth_oauthlib.flow import InstalledAppFlow
  6. from google.auth.transport.requests import Request
  7. from apiclient import discovery
  8. import httplib2
  9. import os,sys
  10. import base64
  11. #from bs4 import BeautifulSoup
  12. from collections import OrderedDict
  13. # If modifying these scopes, delete the file token.pickle.
  14. SCOPES = ['https://www.googleapis.com/auth/gmail.modify']
  15. def main():
  16. pathJson = "C:\\Users\\chris\\OneDrive\\Documentos\\GitHub\\MOBEES-BR\\Backend\\dsp\\adm\\auth\\credentials_mail.json"
  17. pathPickle = "C:\\Users\\chris\\OneDrive\\Documentos\\GitHub\\MOBEES-BR\\Backend\\dsp\\adm\\auth\\token_mail.pickle"
  18. creds = None
  19. # The file token.pickle stores the user's access and refresh tokens, and is
  20. # created automatically when the authorization flow completes for the first
  21. # time.
  22. if os.path.exists(pathPickle):
  23. with open(pathPickle, 'rb') as token:
  24. creds = pickle.load(token)
  25. # If there are no (valid) credentials available, let the user log in.
  26. if not creds or not creds.valid:
  27. if creds and creds.expired and creds.refresh_token:
  28. creds.refresh(Request())
  29. else:
  30. flow = InstalledAppFlow.from_client_secrets_file(
  31. pathJson, SCOPES)
  32. creds = flow.run_local_server(port=0)
  33. with open(pathPickle, 'wb') as token:
  34. pickle.dump(creds, token)
  35. service = build('gmail', 'v1', credentials=creds)
  36. # request a list of all the messages
  37. result = service.users().messages().list(userId='me',q='from:mailer-daemon subject:Failure').execute()
  38. # We can also pass maxResults to get any number of emails. Like this:
  39. #result = service.users().messages().list(maxResults=10, userId='me', q='from:mailer-daemon subject:Failure').execute()
  40. messages = result.get('messages')
  41. # messages is a list of dictionaries where each dictionary contains a message id.
  42. email_dest = []
  43. for msg in messages:
  44. # Get the message from its id
  45. txt = service.users().messages().get(userId='me', id=msg['id']).execute()
  46. # Use try-except to avoid any Errors
  47. try:
  48. # Get value of 'payload' from dictionary 'txt'
  49. payload = txt['payload']
  50. headers = payload['headers']
  51. # Look for Subject and Sender Email in the headers
  52. for d in headers:
  53. if d['name'] == 'X-Failed-Recipients':
  54. email_dest.append(d['value'])
  55. break
  56. # The Body of the message is in Encrypted format. So, we have to decode it.
  57. # Get the data and decode it with base 64 decoder.
  58. #parts = payload.get('parts')[0]
  59. #parts = parts['parts'][0]
  60. #data = parts['parts'][0]['body']['data']
  61. #data = data.replace("-","+").replace("_","/")
  62. #decoded_data = base64.b64decode(data)
  63. # Now, the data obtained is in lxml. So, we will parse
  64. # it with BeautifulSoup library
  65. #soup = BeautifulSoup(decoded_data , "lxml")
  66. #body = soup.body()
  67. # Printing the subject, sender's email and message
  68. #print("Subject: ", subject)
  69. #print("From: ", sender)
  70. #print("Message: ", body)
  71. #print('\n')
  72. except BaseException as error:
  73. try:
  74. exc_type, exc_obj, exc_tb = sys.exc_info()
  75. fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
  76. print("ERRO: %s | %s | %s | %s" % (error, exc_type, fname, exc_tb.tb_lineno))
  77. pass
  78. except:
  79. pass
  80. print("Email Dest: ",list(OrderedDict.fromkeys(email_dest)))
  81. if __name__ == '__main__':
  82. main()