Advertisement
Guest User

Untitled

a guest
Mar 5th, 2016
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. import time
  2. from itertools import chain
  3. import email
  4. import imaplib
  5.  
  6. imap_ssl_host = 'imap.gmail.com' # imap.mail.yahoo.com
  7. imap_ssl_port = 993
  8. username = 'USERNAME or EMAIL ADDRESS'
  9. password = 'PASSWORD'
  10.  
  11. # Restrict mail search. Be very specific.
  12. # Machine should be very selective to receive messages.
  13. criteria = {
  14. 'FROM': 'PRIVILEGED EMAIL ADDRESS',
  15. 'SUBJECT': 'SPECIAL SUBJECT LINE',
  16. 'BODY': 'SECRET SIGNATURE',
  17. }
  18. uid_max = 0
  19.  
  20.  
  21. def search_string(uid_max, criteria):
  22. c = list(map(lambda t: (t[0], '"'+str(t[1])+'"'), criteria.items())) + [('UID', '%d:*' % (uid_max+1))]
  23. return '(%s)' % ' '.join(chain(*c))
  24. # Produce search string in IMAP format:
  25. # e.g. (FROM "me@gmail.com" SUBJECT "abcde" BODY "123456789" UID 9999:*)
  26.  
  27.  
  28. def get_first_text_block(msg):
  29. type = msg.get_content_maintype()
  30.  
  31. if type == 'multipart':
  32. for part in msg.get_payload():
  33. if part.get_content_maintype() == 'text':
  34. return part.get_payload()
  35. elif type == 'text':
  36. return msg.get_payload()
  37.  
  38.  
  39. server = imaplib.IMAP4_SSL(imap_ssl_host, imap_ssl_port)
  40. server.login(username, password)
  41. server.select('INBOX')
  42.  
  43. result, data = server.uid('search', None, search_string(uid_max, criteria))
  44.  
  45. uids = [int(s) for s in data[0].split()]
  46. if uids:
  47. uid_max = max(uids)
  48. # Initialize `uid_max`. Any UID less than or equal to `uid_max` will be ignored subsequently.
  49.  
  50. server.logout()
  51.  
  52.  
  53. # Keep checking messages ...
  54. # I don't like using IDLE because Yahoo does not support it.
  55. while 1:
  56. # Have to login/logout each time because that's the only way to get fresh results.
  57.  
  58. server = imaplib.IMAP4_SSL(imap_ssl_host, imap_ssl_port)
  59. server.login(username, password)
  60. server.select('INBOX')
  61.  
  62. result, data = server.uid('search', None, search_string(uid_max, criteria))
  63.  
  64. uids = [int(s) for s in data[0].split()]
  65. for uid in uids:
  66. # Have to check again because Gmail sometimes does not obey UID criterion.
  67. if uid > uid_max:
  68. result, data = server.uid('fetch', uid, '(RFC822)') # fetch entire message
  69. msg = email.message_from_string(data[0][1])
  70.  
  71. uid_max = uid
  72.  
  73. text = get_first_text_block(msg)
  74. print 'New message :::::::::::::::::::::'
  75. print text
  76.  
  77. server.logout()
  78. time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement