win32-pop3-notifier / notifier.pyw

"""
Notificador de novos emails, via pop3, para Windows.
Testado no WindowsXP com Python 7!
Necessita: http://datavibe.net/~essiene/pysystray/
"""

__autor__ = 'Sérgio Hilton Berlotto Junior'
__url__ = 'http://pythonrs.wordpress.com'
__licence__ = 'GPLv3'

from systray import systray
import poplib
import configuracao
import time
import logging
from logging.handlers import RotatingFileHandler

NOEMAILICO = "icons/email-no.ico"
EMAILICO = "icons/mail-new.ico"
LOG_FILENAME = "notifier.log"
LOGNIVEL = logging.INFO

log = logging.getLogger("Notifier")
log.setLevel(LOGNIVEL)

# Add the log message handler to the logger
formatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s",'%a, %d %b %Y %H:%M:%S')
handler = RotatingFileHandler(LOG_FILENAME, maxBytes=2300, backupCount=5)
handler.setFormatter(formatter)
handler.setLevel(LOGNIVEL)
log.addHandler(handler)
				
#print configuracao.host, configuracao.usuario, configuracao.senha

log.info("Variaveis para comparação da caixa...")
E_LEN = 0
E_SIZ = 0
E_DIF = 0


def ver_email():
    global E_LEN, E_SIZ, E_DIF, log
    try: 
        log.info("Conectando a caixa")
        pop = poplib.POP3(configuracao.host) 
    except Exception as e: 
        log.error("Erro na ao conectar ao servidor!")
        log.exception(e)
        return False
        #raise StandardError, "Could not establish connection to %s for password check" % configuracao.host

    try: 
        # Log in and perform a small sanity check 
        log.info("Informando usuário e senha")
        pop.user(configuracao.usuario) 
        pop.pass_(configuracao.senha) 
        log.info("Usuário e senha informados OK!")
        length, size = pop.stat() 
        assert type(length) == type(size) == type(0) 
        log.debug(length, size)
        pop.quit()
        log.info("Vai validar novos emails!")
        if length > E_LEN and size > E_SIZ:
            E_DIF = length - E_LEN
            E_LEN, E_SIZ = length, size
            return True
        else:
            E_DIF = 0
            E_LEN, E_SIZ = length, size
            return False
    except Exception as e: 
        log.error("Erro ao processar o número de emails!")
        log.exception(e)
        raise StandardError, "Could not verify identity. \nUser name %s or password incorrect." % configuracao.usuario 
        pop.quit()
        return False
    """
    numMessages = len(pop.list()[1])
    for i in range(numMessages):
        for j in M.retr(i+1)[1]:
            print j
    """
            
@systray.threaded
def on_load(s):
    while True:
        if ver_email():
            s.icon = EMAILICO
            s.show_info( "Tem novos %s emails!" % str(E_DIF) )
        else:
            if configuracao.voltar_icone:
                s.icon = NOEMAILICO
        log.debug("Aguarda %s segundos" % configuracao.intervalo)
        time.sleep(configuracao.intervalo)

def on_dbl_click(s):
    #só limpa o icone quando der 2Cliques no icone
    log.debug("limpou...")
    s.icon = NOEMAILICO

log.info("Iniciando a aplicação...")
notifier_app = systray.App('Notificador de Emails', 'icons/email-no.ico')
notifier_app.on_load = on_load
notifier_app.on_double_click = on_dbl_click
log.info("Start!")
notifier_app.start()
log.info("Fim")
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.