Advertisement
Guest User

Untitled

a guest
May 25th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #!/usr/env/python
  2.  
  3. # Simple script to manage emails since thunderbird filters kind of suck.
  4. # TODO:
  5. # - log exceptons
  6. # - logging... in general.
  7. # - don't exit on server errors.
  8.  
  9. import imaplib
  10. import email
  11. import logging
  12. import traceback
  13. from time import sleep
  14.  
  15.  
  16. _USER = ""
  17. _PASS = ""
  18. _SERVER = ""
  19.  
  20. def check_field(a, b):
  21. # So we don't throw errors in an if statement when checking against NoneType (non iterable)
  22. if b:
  23. if a in b:
  24. return True
  25. return False
  26.  
  27.  
  28. def get_text(msg):
  29. # Returns plaintext first part of email (should be the whole body -- not actually sure.)
  30. if msg.is_multipart():
  31. return get_text(msg.get_payload(0))
  32. else:
  33. return msg.get_payload(None, True)
  34.  
  35.  
  36. def filter_email(m, uid, msg):
  37.  
  38. move = None # Folder to move the email to.
  39. seen = False # Mark the message as seen or not.
  40. body = get_text(msg)
  41.  
  42.  
  43. #-----------------------------------------------------------------------------------------
  44. # FILTERS HERE
  45. # eg:
  46.  
  47. # elif check_field("noreply", msg[ "from" ]):
  48. # move = "Sort/To/Folder"
  49.  
  50. # if check_field("Password reset", msg[ "subject" ]):
  51. # seen = False
  52. #-----------------------------------------------------------------------------------------
  53.  
  54.  
  55. if not seen:
  56. m.uid( "STORE", uid, "-FLAGS", "(\Seen)" )
  57.  
  58. if move:
  59. retcode, data = m.uid( "COPY", uid, move )
  60. if retcode == "OK":
  61. m.uid( "STORE", uid, "+FLAGS", "(\Deleted)" )
  62.  
  63.  
  64. m = imaplib.IMAP4_SSL(_SERVER)
  65. retcode, capabilities = m.login( _USER, _PASS )
  66.  
  67. m.select() # Set mailbox (to INBOX by default)
  68.  
  69. try:
  70. while 1:
  71. retcode, messages = m.uid( "SEARCH", None, "(UNSEEN)" )
  72.  
  73. if retcode == "OK" and messages[ 0 ]:
  74. for uid in messages[ 0 ].split( " " ):
  75. typ, data = m.uid( "FETCH", uid,"(RFC822)" )
  76. msg = email.message_from_string( data[ 0 ][ 1 ] )
  77.  
  78. filter_email( m, uid, msg )
  79.  
  80. m.expunge()
  81. sleep( 30 )
  82. except:
  83. # TODO: log exception here
  84. m.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement