gmail_msg.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. from apiclient import errors
  2. def ListMessagesMatchingQuery(service, user_id, query=''):
  3. """List all Messages of the user's mailbox matching the query.
  4. Args:
  5. service: Authorized Gmail API service instance.
  6. user_id: User's email address. The special value "me"
  7. can be used to indicate the authenticated user.
  8. query: String used to filter messages returned.
  9. Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
  10. Returns:
  11. List of Messages that match the criteria of the query. Note that the
  12. returned list contains Message IDs, you must use get with the
  13. appropriate ID to get the details of a Message.
  14. """
  15. try:
  16. response = service.users().messages().list(userId=user_id, q=query).execute()
  17. messages = []
  18. if 'messages' in response:
  19. messages.extend(response['messages'])
  20. while 'nextPageToken' in response:
  21. page_token = response['nextPageToken']
  22. response = service.users().messages().list(userId=user_id, q=query, pageToken=page_token).execute()
  23. messages.extend(response['messages'])
  24. return messages
  25. except errors.HttpError:
  26. print('An error occurred: %s' % error)
  27. def ListMessagesWithLabels(service, user_id, label_ids=[]):
  28. """List all Messages of the user's mailbox with label_ids applied.
  29. Args:
  30. service: Authorized Gmail API service instance.
  31. user_id: User's email address. The special value "me"
  32. can be used to indicate the authenticated user.
  33. label_ids: Only return Messages with these labelIds applied.
  34. Returns:
  35. List of Messages that have all required Labels applied. Note that the
  36. returned list contains Message IDs, you must use get with the
  37. appropriate id to get the details of a Message.
  38. """
  39. try:
  40. response = service.users().messages().list(userId=user_id, labelIds=label_ids).execute()
  41. messages = []
  42. if 'messages' in response:
  43. messages.extend(response['messages'])
  44. while 'nextPageToken' in response:
  45. page_token = response['nextPageToken']
  46. response = service.users().messages().list(userId=user_id,
  47. labelIds=label_ids,
  48. pageToken=page_token).execute()
  49. messages.extend(response['messages'])
  50. return messages
  51. except errors.HttpError:
  52. print('An error occurred: %s' % error)
  53. """Get Message with given ID.
  54. """
  55. import base64
  56. import email
  57. from apiclient import errors
  58. def GetMessage(service, user_id, msg_id):
  59. """Get a Message with given ID.
  60. Args:
  61. service: Authorized Gmail API service instance.
  62. user_id: User's email address. The special value "me"
  63. can be used to indicate the authenticated user.
  64. msg_id: The ID of the Message required.
  65. Returns:
  66. A Message.
  67. """
  68. try:
  69. message = service.users().messages().get(userId=user_id, id=msg_id).execute()
  70. return message
  71. except errors.HttpError:
  72. print('An error occurred: %s' % error)
  73. def get_message_header(message):
  74. return message['payload']['headers']
  75. def GetMimeMessage(service, user_id, msg_id):
  76. """Get a Message and use it to create a MIME Message.
  77. Args:
  78. service: Authorized Gmail API service instance.
  79. user_id: User's email address. The special value "me"
  80. can be used to indicate the authenticated user.
  81. msg_id: The ID of the Message required.
  82. Returns:
  83. A MIME Message, consisting of data from Message.
  84. """
  85. try:
  86. message = service.users().messages().get(userId=user_id, id=msg_id,
  87. format='raw').execute()
  88. #print 'Message snippet: %s' % message['snippet']
  89. msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
  90. mime_msg = email.message_from_string(msg_str.decode())
  91. return mime_msg
  92. except errors.HttpError:
  93. print('An error occurred: %s' % error)
  94. def get_message_body(mime_msg):
  95. body = ""
  96. if mime_msg.is_multipart():
  97. for part in mime_msg.walk():
  98. ctype = part.get_content_type()
  99. cdispo = str(part.get('Content-Disposition'))
  100. # skip any text/plain (txt) attachments
  101. if ctype == 'text/plain' and 'attachment' not in cdispo:
  102. body = part.get_payload()
  103. break
  104. # not multipart - i.e. plain text, no attachments, keeping fingers crossed
  105. else:
  106. body = mime_msg.get_payload()
  107. #print 'Message body: %s' % body
  108. return body