Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/env/python
- # Simple script to manage emails since thunderbird filters kind of suck.
- # TODO:
- # - log exceptons
- # - logging... in general.
- # - don't exit on server errors.
- import imaplib
- import email
- import logging
- import traceback
- from time import sleep
- _USER = ""
- _PASS = ""
- _SERVER = ""
- def check_field(a, b):
- # So we don't throw errors in an if statement when checking against NoneType (non iterable)
- if b:
- if a in b:
- return True
- return False
- def get_text(msg):
- # Returns plaintext first part of email (should be the whole body -- not actually sure.)
- if msg.is_multipart():
- return get_text(msg.get_payload(0))
- else:
- return msg.get_payload(None, True)
- def filter_email(m, uid, msg):
- move = None # Folder to move the email to.
- seen = False # Mark the message as seen or not.
- body = get_text(msg)
- #-----------------------------------------------------------------------------------------
- # FILTERS HERE
- # eg:
- # elif check_field("noreply", msg[ "from" ]):
- # move = "Sort/To/Folder"
- # if check_field("Password reset", msg[ "subject" ]):
- # seen = False
- #-----------------------------------------------------------------------------------------
- if not seen:
- m.uid( "STORE", uid, "-FLAGS", "(\Seen)" )
- if move:
- retcode, data = m.uid( "COPY", uid, move )
- if retcode == "OK":
- m.uid( "STORE", uid, "+FLAGS", "(\Deleted)" )
- m = imaplib.IMAP4_SSL(_SERVER)
- retcode, capabilities = m.login( _USER, _PASS )
- m.select() # Set mailbox (to INBOX by default)
- try:
- while 1:
- retcode, messages = m.uid( "SEARCH", None, "(UNSEEN)" )
- if retcode == "OK" and messages[ 0 ]:
- for uid in messages[ 0 ].split( " " ):
- typ, data = m.uid( "FETCH", uid,"(RFC822)" )
- msg = email.message_from_string( data[ 0 ][ 1 ] )
- filter_email( m, uid, msg )
- m.expunge()
- sleep( 30 )
- except:
- # TODO: log exception here
- m.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement