Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- #coding=utf-8
- """
- IMAP4 Client the fetches emails from a specific INBOX every given time
- """
- #Import built-in modules
- import os
- import sys
- import time
- #Custom modules for config an data handling
- #from Config import retCredentials
- #import Config
- import messageParser
- import dbclient
- from twisted.internet.protocol import Protocol, ReconnectingClientFactory
- from twisted.internet.task import LoopingCall
- from twisted.application import internet, service
- from twisted.internet import protocol, defer, reactor
- from twisted.mail import imap4
- from twisted.python import util, log
- from twisted.python.log import ILogObserver, FileLogObserver
- from twisted.python.logfile import DailyLogFile
- debug = 1
- import ConfigParser
- #import Parser
- #Path default para el archivo de configuracion
- CONFIG_DIR = (
- os.path.join(os.path.dirname(__file__), 'etc/'),
- )
- CONFIG_FILENAME = 'emailparser.conf'
- config = ConfigParser.RawConfigParser()
- config.read(CONFIG_DIR[0]+CONFIG_FILENAME)
- creds = dict( zip(
- ( 'server', 'mailbox', 'password' ),
- ( config.get('account', 'server'),
- config.get('account', 'mailbox'),
- config.get('account', 'password') )
- )
- )
- def retCredentials():
- return creds
- class IMAP4Client(imap4.IMAP4Client):
- def serverGreeting(self,caps):
- """
- Method called when server answers
- """
- if debug: print "On serverGreeting"
- self.serverCapabilities = caps
- if self.greetDeferred is not None:
- d, self.greetDeferred = self.greetDeferred, None
- d.addCallback(self.cbLogin)
- d.addErrback(self.ebProtocolGreeting)
- d.callback(self)
- def ebProtocolGreeting(self, reason):
- log.startLogging(sys.stdout)
- print "Error caought at %s" % time.asctime(time.localtime(time.time()))
- log.err(reason)
- reator.stop()
- def cbLogin(self, proto):
- """
- Callback to IMAP login
- """
- if debug: print "On Login"
- login = self.login(self.factory.username, self.factory.password)
- login.addCallback(self.startPolling)
- login.addErrback(self.cbLoginError)
- def cbLoginError(self, reason):
- log.startLogging(sys.stdout)
- print "Error cauth at %s" % time.asctime(time.localtime(time.time()))
- log.err(reason)
- reactor.stop()
- def connectionLost(self,reason):
- imap4.IMAP4Client.connectionLost(self, reason)
- print "Disconnected at: %s" % time.asctime(time.localtime(time.time()))
- def startPolling(self, proto):
- """
- Callback to poll every x seconds
- """
- call = LoopingCall(self.selectMailbox,mailbox="INBOX")
- call.start(15, now=True)
- def selectMailbox(self, mailbox):
- """
- Select the mailbox to examin
- """
- if debug: print "On selectMailbox"
- mailbox = self.factory.mailbox
- return self.select(mailbox).addCallback(self.cbSelectSuccess)
- def cbSelectSuccess(self, selected):
- """
- Examine the INBOX mailbox for new mails
- """
- if debug: print "On cbSelectSuccess"
- self.messageCount = selected['EXISTS']
- print "Messages: ", self.messageCount
- unseen = imap4.Query(unseen=True)
- return self.search(unseen
- ).addCallback(self.cbSearch)
- def cbSearch(self,messages):
- if debug: print "on cbSearch"
- messageSet = imap4.MessageSet()
- for message in messages:
- messageSet += message
- if messageSet:
- self.fetchMessage(messageSet, False
- ).addCallback(self.cbProcMessage)
- else:
- return
- def cbProcMessage(self, messages):
- if debug: print "on cbProcEnvelop"
- for message in messages.iteritems():
- body = message[1]['RFC822']
- #print body
- num = messageParser.searchNumber(body)
- sender = messageParser.searchEmail(body)
- print "Ingresando en al DB: \n"
- print num, sender
- dbclient.insertData(num, sender)
- class IMAP4ClientFactory(ReconnectingClientFactory):
- protocol = IMAP4Client
- def __init__(self, username, password, onConn):
- self.username = username
- self.password = password
- self.mailbox = 'INBOX'
- self.onConn = onConn
- def startedConnecting(self, connector):
- print 'Started to connect'
- def buildProtocol(self,addr):
- if debug: print "On buildProtocol"
- p = self.protocol()
- p.factory = self
- p.greetDeferred = self.onConn
- auth = imap4.CramMD5ClientAuthenticator(self.username)
- p.registerAuthenticator(auth)
- print 'Connected'
- print 'Resetting connection delay'
- return p
- def clientConnectionLost(self, connector, reason):
- print 'Connection Lost: Reason: ', reason
- ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
- def clientConectionFailed(self, connector, reason):
- print 'Connection Failed: Reason: ', reason
- ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
- def ebConnection(reason):
- log.startLogging(sys.stdout)
- log.err(reason)
- reactor.stop()
- PORT = 143
- RESULT = "INBOX"
- credentials = retCredentials()
- hostname = credentials['server']
- username = credentials['mailbox']
- password = credentials['password']
- onConn = defer.Deferred(
- ).addErrback(ebConnection
- )
- #Starting the service client
- application = service.Application('IMAP4Client')
- logFile = DailyLogFile("pushmail.log", "log")
- application.setComponent(ILogObserver,FileLogObserver(logFile).emit)
- factory = IMAP4ClientFactory(username, password, onConn)
- internet.TCPClient(hostname, PORT, factory).setServiceParent(
- service.IServiceCollection(application))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement