#!/usr/bin/python

"""
    imapQuotaChecker.py 1.0
    Last updated: June 08, 2006
    Copyright (c) 2006 http://www.broobles.com/
    Website: http://www.broobles.com/scripts/imapquotachecker/
    
    Description:
    ===========
    Checks the quota of an IMAP account and sends an email notification if the 
    specified quota warning level has been breached.
    
    Usage:
    =====
    - Modify the IMAP and SMTP parameters below (after the import statements)
    - Upload the script into a non-public location on your webserver
    - Create a cron job to invoke the script as often as you wish
    
    History:
    =======
    1.0  (June 8, 2006): 
        - Initial Release
    
    Licence:
    =======
    This script is free software; you can redistribute it and/or modify it under the terms of  
    the GNU Lesser General Public License as published by the Free Software Foundation;         
    either version 2.1 of the License, or (at your option) any later version.                  
    Please visit http://www.gnu.org/copyleft/lesser.html for more information.    

"""

import imaplib, smtplib, re
from email.Utils import formatdate

# Quota percentage above which a notification will be sent
breach_level=90     

# Parameters of the account to check the quota for
imap_host="yourhost.com"
imap_user="username"
imap_pswd="password"

# Email address to send notifications to
send_address="you@domain.com"

# SMTP Parameters
smtp_host="yoursmtpserver.com"
smtp_authentication = 1  # set to 1 if your SMTP server requires authentication, 0 if not
# Following used only when authentication is set to 1
smtp_user="username"    
smtp_pass="password"            


def main():
    imap = imaplib.IMAP4(imap_host)
    try:
        imap.login(imap_user,imap_pswd)
        quotaStr = imap.getquotaroot("INBOX") [1][1][0]
        p = re.compile('\d+')
        r = p.findall(quotaStr)
        fQuota = (float(r[0])/float(r[1])) * 100
        if fQuota > breach_level:
            emailNotification(fQuota)
    finally:
        imap.logout()
        
def emailNotification(quota):
    """ Email the notification """
    # Form the message
    headers =  "From: %s\r\n" % send_address
    headers += "To: %s\r\n" % send_address
    headers += "Date: %s\r\n" % formatdate()
    headers += "Subject: IMAP Quota Check WARNING [%4.2f%%]\r\n" % quota
    body = "Your account on %s is above the warning limit, the quota is currently at %4.2f%%" % (imap_host,quota)
    fullMessage = headers + "\r\n" + body + "\r\n.\r\n"
    
    # Send it
    smtpsession = smtplib.SMTP(smtp_host)
    try:
        if smtp_authentication:
            smtpsession.login(smtp_user,smtp_pass)
        smtpresult = smtpsession.sendmail("%s" % send_address, "%s" % send_address, fullMessage)
    finally:
        try: smtpsession.quit()
        except: pass    

if __name__ == '__main__': main()