gmail.py 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from __future__ import print_function
  2. import httplib2
  3. import os
  4. from apiclient import discovery
  5. import oauth2client
  6. from oauth2client import client
  7. from oauth2client import tools
  8. from gmail_msg import *
  9. from event import *
  10. from datetime import datetime
  11. try:
  12. import argparse
  13. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  14. except ImportError:
  15. flags = None
  16. # If modifying these scopes, delete your previously saved credentials
  17. # at ~/.credentials/projet-wdm-gmail.json
  18. SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
  19. CLIENT_SECRET_FILE = 'client_secret.json'
  20. APPLICATION_NAME = 'Gmail API Python'
  21. def get_credentials():
  22. """Gets valid user credentials from storage.
  23. If nothing has been stored, or if the stored credentials are invalid,
  24. the OAuth2 flow is completed to obtain the new credentials.
  25. Returns:
  26. Credentials, the obtained credential.
  27. """
  28. home_dir = os.path.expanduser('~')
  29. credential_dir = os.path.join(home_dir, '.credentials')
  30. if not os.path.exists(credential_dir):
  31. os.makedirs(credential_dir)
  32. credential_path = os.path.join(credential_dir, 'projet-wdm-gmail.json')
  33. store = oauth2client.file.Storage(credential_path)
  34. credentials = store.get()
  35. if not credentials or credentials.invalid:
  36. flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
  37. flow.user_agent = APPLICATION_NAME
  38. if flags:
  39. credentials = tools.run_flow(flow, store, flags)
  40. else: # Needed only for compatibility with Python 2.6
  41. credentials = tools.run(flow, store)
  42. print('Storing credentials to ' + credential_path)
  43. return credentials
  44. def get_list_event_gmail():
  45. credentials = get_credentials()
  46. http = credentials.authorize(httplib2.Http())
  47. service = discovery.build('gmail', 'v1', http=http)
  48. results = service.users().labels().list(userId='me').execute()
  49. labels = results.get('labels', [])
  50. list_event = []
  51. if not labels:
  52. print('No labels found.')
  53. return list_event
  54. for label in labels:
  55. if (label['name']=='INBOX'):
  56. list_msg = ListMessagesMatchingQuery(service,"me", query="Rendez-vous")
  57. for msg in list_msg:
  58. msg = GetMessage(service,"me",msg['id'])
  59. mime_msg = GetMimeMessage(service,"me",msg['id'])
  60. body = get_message_body(mime_msg)
  61. try:
  62. # Parse only messages in the format + not lenient (do not check keywords etc)
  63. # Rendez-vous
  64. # le 22/02/2016 11h00
  65. # à l'université Paris Diderot
  66. # pour le cours de WDM
  67. lines = body.replace('\r', '').split('\n')
  68. if len(lines) >= 4 and lines[0] == 'Rendez-vous':
  69. date = datetime.strptime(lines[1][3:], '%d/%m/%Y %Hh%M')
  70. location = lines[2][2:]
  71. description = lines[3]
  72. list_event.append(Event('gmail_'+msg['id'], date,location,description))
  73. except Exception as e:
  74. raise e
  75. return list_event