Advertisement
Guest User

Untitled

a guest
Feb 24th, 2011
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.20 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #coding=utf-8
  3.  
  4.  
  5. """
  6. IMAP4 Client the fetches emails from a specific INBOX every given time
  7. """
  8. #Import built-in modules
  9. import os
  10. import sys
  11. import time
  12. #Custom modules for config an data handling
  13. #from Config import retCredentials
  14. #import Config
  15. import messageParser
  16. import dbclient
  17.  
  18. from twisted.internet.protocol import Protocol, ReconnectingClientFactory
  19. from twisted.internet.task import LoopingCall
  20. from twisted.application import internet, service
  21. from twisted.internet import protocol, defer, reactor
  22. from twisted.mail import imap4
  23. from twisted.python import util, log
  24. from twisted.python.log import ILogObserver, FileLogObserver
  25. from twisted.python.logfile import DailyLogFile
  26. debug = 1
  27.  
  28. import ConfigParser
  29. #import Parser
  30.  
  31. #Path default para el archivo de configuracion
  32.  
  33. CONFIG_DIR = (
  34.             os.path.join(os.path.dirname(__file__), 'etc/'),
  35.             )
  36.  
  37. CONFIG_FILENAME = 'emailparser.conf'
  38.  
  39.  
  40. config = ConfigParser.RawConfigParser()
  41. config.read(CONFIG_DIR[0]+CONFIG_FILENAME)
  42. creds = dict( zip(
  43.                  ( 'server', 'mailbox', 'password' ),  
  44.                  ( config.get('account', 'server'),
  45.                    config.get('account', 'mailbox'),
  46.                    config.get('account', 'password') )
  47.                  )
  48.             )
  49.  
  50.  
  51. def retCredentials():
  52.     return creds
  53.  
  54.  
  55. class IMAP4Client(imap4.IMAP4Client):
  56.  
  57.     def serverGreeting(self,caps):
  58.         """
  59.        Method called when server answers
  60.        """
  61.         if debug: print "On serverGreeting"
  62.  
  63.         self.serverCapabilities = caps
  64.         if self.greetDeferred is not None:
  65.             d, self.greetDeferred = self.greetDeferred, None
  66.             d.addCallback(self.cbLogin)
  67.             d.addErrback(self.ebProtocolGreeting)
  68.             d.callback(self)
  69.    
  70.     def ebProtocolGreeting(self, reason):
  71.         log.startLogging(sys.stdout)
  72.         print "Error caought at %s" % time.asctime(time.localtime(time.time()))
  73.         log.err(reason)
  74.         reator.stop()
  75.  
  76.  
  77.     def cbLogin(self, proto):
  78.         """
  79.        Callback to IMAP login
  80.        """
  81.         if debug: print "On Login"
  82.  
  83.         login =  self.login(self.factory.username, self.factory.password)
  84.         login.addCallback(self.startPolling)
  85.         login.addErrback(self.cbLoginError)
  86.        
  87.     def cbLoginError(self, reason):
  88.         log.startLogging(sys.stdout)
  89.         print "Error cauth at %s" % time.asctime(time.localtime(time.time()))
  90.         log.err(reason)
  91.         reactor.stop()
  92.        
  93.     def connectionLost(self,reason):
  94.         imap4.IMAP4Client.connectionLost(self, reason)
  95.         print "Disconnected at: %s" % time.asctime(time.localtime(time.time()))
  96.        
  97.     def startPolling(self, proto):
  98.         """
  99.        Callback to poll every x seconds
  100.        """
  101.         call = LoopingCall(self.selectMailbox,mailbox="INBOX")
  102.         call.start(15, now=True)
  103.        
  104.        
  105.     def selectMailbox(self, mailbox):
  106.         """
  107.        Select the mailbox to examin
  108.        """
  109.         if debug: print "On selectMailbox"
  110.  
  111.         mailbox = self.factory.mailbox
  112.         return self.select(mailbox).addCallback(self.cbSelectSuccess)
  113.  
  114.        
  115.  
  116.     def cbSelectSuccess(self, selected):
  117.         """
  118.        Examine the INBOX mailbox for new mails
  119.  
  120.        """
  121.         if debug: print "On cbSelectSuccess"
  122.  
  123.  
  124.         self.messageCount = selected['EXISTS']
  125.         print "Messages: ", self.messageCount
  126.  
  127.         unseen = imap4.Query(unseen=True)
  128.  
  129.         return self.search(unseen
  130.             ).addCallback(self.cbSearch)
  131.  
  132.     def cbSearch(self,messages):
  133.         if debug: print "on cbSearch"
  134.  
  135.         messageSet = imap4.MessageSet()
  136.  
  137.         for message in messages:
  138.             messageSet += message
  139.  
  140.         if messageSet:
  141.            
  142.  
  143.             self.fetchMessage(messageSet, False
  144.                 ).addCallback(self.cbProcMessage)
  145.         else:
  146.             return
  147.  
  148.  
  149.     def cbProcMessage(self, messages):
  150.         if debug: print "on cbProcEnvelop"
  151.        
  152.         for message in messages.iteritems():
  153.  
  154.            
  155.             body = message[1]['RFC822']
  156.             #print body
  157.            
  158.             num = messageParser.searchNumber(body)
  159.             sender = messageParser.searchEmail(body)
  160.  
  161.             print "Ingresando en al DB: \n"
  162.             print num, sender
  163.             dbclient.insertData(num, sender)
  164.  
  165.  
  166. class IMAP4ClientFactory(ReconnectingClientFactory):
  167.  
  168.     protocol = IMAP4Client
  169.  
  170.     def __init__(self, username, password,  onConn):
  171.  
  172.         self.username = username
  173.         self.password = password
  174.         self.mailbox = 'INBOX'
  175.         self.onConn = onConn
  176.        
  177.     def startedConnecting(self, connector):
  178.         print 'Started to connect'
  179.  
  180.     def buildProtocol(self,addr):
  181.         if debug: print "On buildProtocol"
  182.         p = self.protocol()
  183.         p.factory = self
  184.         p.greetDeferred = self.onConn
  185.         auth = imap4.CramMD5ClientAuthenticator(self.username)
  186.         p.registerAuthenticator(auth)
  187.        
  188.         print 'Connected'
  189.         print 'Resetting connection delay'
  190.  
  191.         return p
  192.    
  193.     def clientConnectionLost(self, connector, reason):
  194.         print 'Connection Lost: Reason: ', reason
  195.         ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
  196.  
  197.     def clientConectionFailed(self, connector, reason):
  198.         print 'Connection Failed: Reason: ', reason
  199.         ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
  200.  
  201.  
  202. def ebConnection(reason):
  203.     log.startLogging(sys.stdout)
  204.     log.err(reason)
  205.     reactor.stop()
  206.  
  207.  
  208.  
  209. PORT = 143
  210. RESULT = "INBOX"
  211.  
  212.  
  213. credentials = retCredentials()
  214. hostname = credentials['server']
  215. username = credentials['mailbox']
  216. password = credentials['password']
  217.  
  218. onConn = defer.Deferred(
  219.         ).addErrback(ebConnection
  220.         )
  221.  
  222. #Starting the service client
  223.  
  224. application = service.Application('IMAP4Client')
  225. logFile = DailyLogFile("pushmail.log", "log")
  226. application.setComponent(ILogObserver,FileLogObserver(logFile).emit)
  227. factory = IMAP4ClientFactory(username, password, onConn)
  228. internet.TCPClient(hostname, PORT, factory).setServiceParent(
  229.         service.IServiceCollection(application))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement