daily pastebin goal
32%
SHARE
TWEET

GMail Important Mails Notifier

a guest Sep 4th, 2010 131 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """GMail Important Mails Notifier
  4.  
  5. A very simple GMail IMAP client which retrieves
  6. only new **important** messages and displays a
  7. notification using pynotify module.
  8. """
  9. import time
  10. import imaplib
  11. import pynotify
  12. import getpass
  13. from email.header import decode_header
  14. from email.parser import Parser
  15. from optparse import OptionParser
  16.  
  17. __author__ = "Andrés Gattinoni <andresgattinoni@gmail.com>"
  18. __version__ = "0.1"
  19. __host = 'imap.gmail.com'
  20. __port = 993
  21. __interval = 60*2
  22.  
  23. class Client(object):
  24.     """Very simple IMAP client"""
  25.     def __init__ (self, host, port, username, password):
  26.         """Constructor"""
  27.         self._interval = 0
  28.         # Connector
  29.         self.client =  imaplib.IMAP4_SSL(host, port)
  30.         # Login
  31.         if not self.client.login(username, password):
  32.             raise Exception("Invalid login")
  33.         # Attempt to select the Important label
  34.         status, data = self.client.select('[Gmail]/Important')
  35.         if status != 'OK':
  36.             raise Exception("Label [Gmail]/Important not found")
  37.  
  38.         # Attempt to init pynotify
  39.         if not pynotify.init("GMail Important Messages"):
  40.             raise Exception("Failed to initialize pynotify module")
  41.  
  42.     def set_interval (self, time):
  43.         """Define a new check interval"""
  44.         self._interval = int(time)
  45.  
  46.     def start (self):
  47.         """Main loop"""
  48.         lst = []
  49.         while True:
  50.             try:
  51.                 status, data = self.client.search(None, '(UNSEEN)')
  52.                 if status == 'OK':
  53.                     if data[0] != '':
  54.                         for msg_id in sorted(data[0].split()):
  55.                             # If we have a new message
  56.                             # fetch it and append it to the list
  57.                             if msg_id != '' and msg_id not in lst:
  58.                                 lst.append(msg_id)
  59.                                 status, data = self.client.fetch(msg_id, '(RFC822)')
  60.                                 # Mark as unread
  61.                                 self.client.store(msg_id, '-FLAGS', '\\Seen')
  62.                                 self.client.store(msg_id, '-FLAGS', '\\Recent')
  63.                                 if status == 'OK':
  64.                                     msg = Parser().parsestr(data[0][1])
  65.                                     self.notify(self.get_header(msg, 'From'), \
  66.                                                 self.get_header(msg, 'Subject'))
  67.                                 else:
  68.                                     print "Failed to fetch message #%s" % str(msg_id)
  69.                 else:
  70.                     raise Exception("Failed to retrieve new important messages")
  71.                     break
  72.                 time.sleep(self._interval)
  73.             except KeyboardInterrupt:
  74.                 break
  75.  
  76.     def notify (self, title, msg):
  77.         """Notifies new messages"""
  78.         pynotify.Notification(title, msg).show()
  79.  
  80.     def get_header (self, msg, header):
  81.         """Gets a header from a message"""
  82.         header = decode_header(msg.get(header))
  83.         if (header[0][1]):
  84.             return unicode(header[0][0], header[0][1]).encode('utf8')
  85.         else:
  86.             return header[0][0]
  87.  
  88. if __name__ == '__main__':
  89.     """Starting point of the application.
  90.    Defines an option parser and starts the client loop"""
  91.     parser = OptionParser(usage='%prog [options]', \
  92.                           version=__version__, \
  93.                           description="Simple script for Important messages notifications")
  94.     parser.add_option('-u', '--user', dest='user', \
  95.                       help='Gmail\'s username', \
  96.                       metavar='USERNAME', default=None)
  97.     parser.add_option('-p', '--password', dest='password', \
  98.                       help='Gmail\'s password', \
  99.                       metavar='PASSWORD', default=None)
  100.     parser.add_option('-H', '--host', dest='host', \
  101.                       help='IMAP hostname (default: %s)' % __host, \
  102.                       metavar='HOSTNAME', default=__host)
  103.     parser.add_option('-P', '--port', dest='port', \
  104.                       help='IMAP port (default: %d)' % __port, \
  105.                       metavar='PORT', default=__port)
  106.     parser.add_option('-t', '--time', dest='time', \
  107.                       help='Check interval (default: %d secs)' % __interval, \
  108.                       metavar='TIME', default=__interval)
  109.  
  110.     # Parse options and do some input checking
  111.     (option, args) = parser.parse_args()
  112.  
  113.     if option.user is None:
  114.         option.user = raw_input('Username: ')
  115.  
  116.     if option.password is None:
  117.         option.password = getpass.getpass('Password: ')
  118.  
  119.     client = Client(option.host, option.port, option.user, option.password)
  120.     client.set_interval(option.time)
  121.     client.start()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top