"Fossies" - the Fresh Open Source Software Archive

Member "getmail-5.16/getmail_fetch" (31 Oct 2021, 8789 Bytes) of package /linux/misc/getmail-5.16.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the latest Fossies "Diffs" side-by-side code changes report for "getmail_fetch": 5.15_vs_5.16.

    1 #!/usr/bin/env python2
    2 
    3 import sys
    4 
    5 if sys.hexversion < 0x2030300:
    6     raise ImportError('getmail version 5 requires Python version 2.3.3 '
    7                       'or later')
    8 
    9 import os
   10 import socket
   11 import poplib
   12 import new
   13 from optparse import OptionParser
   14 
   15 try:
   16     from getmailcore import __version__, retrievers, destinations, message, \
   17         logging
   18     from getmailcore.exceptions import *
   19 except ImportError, o:
   20     sys.stderr.write('ImportError:  %s\n' % o)
   21     sys.exit(127)
   22 
   23 log = logging.Logger()
   24 log.addhandler(sys.stderr, logging.WARNING)
   25 
   26 #######################################
   27 class dummyInstance:
   28     pass
   29 
   30 #######################################
   31 def blurb():
   32     log.info('getmail_fetch version %s\n' % __version__)
   33     log.info('Copyright (C) 1998-2021 Charles Cazabon.  Licensed under the '
   34              'GNU GPL version 2.\n')
   35 
   36 #######################################
   37 def error_exit(v, s):
   38     sys.stderr.write(s + '\n')
   39     sys.stderr.flush()
   40     sys.exit(v)
   41 
   42 #######################################
   43 def go(retriever, destination, options, startmsg):
   44     msgs_retrieved = 0
   45     if options.verbose:
   46         log.addhandler(sys.stdout, logging.INFO, maxlevel=logging.INFO)
   47     blurb()
   48     try:
   49         if startmsg is not None:
   50             destination.deliver_message(startmsg, False, False)
   51         log.info('%s:\n' % retriever)
   52         retriever.initialize(options)
   53         destination.retriever_info(retriever)
   54         nummsgs = len(retriever)
   55         fmtlen = len(str(nummsgs))
   56         for (msgnum, msgid) in enumerate(retriever):
   57             msgnum += 1
   58             size = retriever.getmsgsize(msgid)
   59             log.info('  msg %*d/%*d (%d bytes) ...'
   60                      % (fmtlen, msgnum, fmtlen, nummsgs, size))
   61             try:
   62                 msg = retriever.getmsg(msgid)
   63                 msgs_retrieved += 1
   64                 destination.deliver_message(msg, False, False)
   65                 log.info(' delivered')
   66                 retriever.delivered(msgid)
   67                 if options.delete:
   68                     retriever.delmsg(msgid)
   69                     log.info(', deleted')
   70                 log.info('\n')
   71 
   72             except getmailDeliveryError, o:
   73                 error_exit(7, 'Delivery error: %s' % o)
   74 
   75         try:
   76             retriever.quit()
   77         except getmailOperationError, o:
   78             log.warning('Operation error during quit (%s)\n' % o)
   79 
   80     except socket.timeout, o:
   81         error_exit(8, 'Timeout error: %s' % o)
   82 
   83     except socket.gaierror, o:
   84         error_exit(9, 'gaierror: %s' % o)
   85 
   86     except socket.error, o:
   87         error_exit(10, 'Socket error: %s' % o)
   88 
   89     except poplib.error_proto, o:
   90         error_exit(11, 'Protocol error: %s' % o)
   91 
   92     except getmailCredentialError, o:
   93         error_exit(13, 'Credential error: %s' % o)
   94 
   95     except getmailOperationError, o:
   96         error_exit(12, 'Operational error: %s' % o)
   97 
   98     log.info('%d messages retrieved\n' % msgs_retrieved)
   99 
  100 #######################################
  101 def main():
  102     try:
  103         parser = OptionParser(
  104             version='%%prog %s' % __version__,
  105             usage='%prog [options] server username password destination'
  106         )
  107         parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
  108                           help='output only on error')
  109         parser.add_option('-v', '--verbose', action='store_true',
  110                           dest='verbose', default=True,
  111                           help='output informational messages '
  112                                '(default: verbose)')
  113         parser.add_option('-m', '--message', action='store', dest='message',
  114                           help='deliver message from FILE first',
  115                           metavar='FILE')
  116         parser.add_option('-p', '--port', action='store', type='int',
  117                           dest='port', metavar='PORT', default=None,
  118                           help='use server port PORT (default: POP: 110, '
  119                                'POP3-over-SSL: 995)')
  120         parser.add_option('-d', '--delete', action='store_true',
  121                           dest='delete', default=False,
  122                           help='delete messages after retrieval (default: no)')
  123         parser.add_option('-t', '--timeout', action='store', type='int',
  124                           dest='timeout', metavar='SECS', default=180,
  125                           help='use timeout SECS (default: 180)')
  126         parser.add_option('-a', '--apop', action='store_true',
  127                           dest='apop', default=False,
  128                           help='use APOP authentication (default: no)')
  129         parser.add_option('-s', '--ssl', action='store_true',
  130                           dest='ssl', default=False,
  131                           help='use POP3-over-SSL (default: no)')
  132         (options, args) = parser.parse_args(sys.argv[1:])
  133         if len(args) != 4:
  134             raise getmailOperationError('incorrect arguments; try --help'
  135                                         % args)
  136 
  137         def get(self, key, value=None):
  138             return getattr(self, key, value)
  139         options.get = new.instancemethod(get, options, options.__class__)
  140 
  141         msg = None
  142         if options.message is not None:
  143             try:
  144                 f = open(options.message, 'rb')
  145                 msg = message.Message(fromfile=f)
  146             except IOError, o:
  147                 error_exit(
  148                     1,
  149                     'Error reading message file "%s": %s' % (options.message, o)
  150                 )
  151 
  152         instance = dummyInstance()
  153 
  154         # Retriever
  155         if options.ssl:
  156             retriever_func = retrievers.BrokenUIDLPOP3SSLRetriever
  157             port = options.port or 995
  158         else:
  159             retriever_func = retrievers.BrokenUIDLPOP3Retriever
  160             port = options.port or 110
  161         retriever_args = {
  162             'getmaildir' : os.getcwd(),
  163             'configparser' : instance,
  164             'timeout' : options.timeout,
  165             'server' : args[0],
  166             'port' : port,
  167             'username' : args[1],
  168             'password' : args[2],
  169             'use_apop' : options.apop
  170         }
  171         try:
  172             retriever = retriever_func(**retriever_args)
  173             retriever.checkconf()
  174         except getmailOperationError, o:
  175             error_exit(3, 'Error initializing retriever: %s' % o)
  176 
  177         # Destination
  178         destination = args[3].strip()
  179         if destination.startswith('.') or destination.startswith('/'):
  180             if destination.endswith('/'):
  181                 destination_func = destinations.Maildir
  182                 destination_args = {
  183                     'path' : destination,
  184                     'configparser' : instance,
  185                 }
  186             else:
  187                 destination_func = destinations.Mboxrd
  188                 destination_args = {
  189                     'path' : destination,
  190                     'configparser' : instance,
  191                 }
  192         elif destination.startswith('|'):
  193             destination_func = destinations.MDA_external
  194             parts = destination[1:].split()
  195             cmd = parts[0]
  196             arguments = str(tuple(parts[1:]))
  197             destination_args = {
  198                 'path' : cmd,
  199                 'arguments' : arguments,
  200                 'allow_root_commands' : False,
  201                 'configparser' : instance,
  202             }
  203         else:
  204             error_exit(4, 'Unknown destination type "%s"' % destination)
  205 
  206         try:
  207             destination = destination_func(**destination_args)
  208         except getmailOperationError, o:
  209             error_exit(
  210                 5, 'Error initializing destination "%s": %s' % (destination, o)
  211             )
  212 
  213         go(retriever, destination, options, msg)
  214 
  215     except KeyboardInterrupt:
  216         error_exit(6, 'Operation aborted by user (keyboard interrupt)')
  217     except getmailOperationError, o:
  218         error_exit(7, 'Operation error: %s' % o)
  219     except getmailConfigurationError, o:
  220         error_exit(8, 'Configuration error: %s' % o)
  221     except StandardError, o:
  222         log.critical('\nException: please read docs/BUGS and include the '
  223                      'following information in any bug report:\n\n')
  224         log.critical('  getmail_fetch version %s\n' % __version__)
  225         log.critical('  Python version %s\n\n' % sys.version)
  226         log.critical('Unhandled exception follows:\n')
  227         exc_type, value, tb = sys.exc_info()
  228         import traceback
  229         tblist = (traceback.format_tb(tb, None)
  230                   + traceback.format_exception_only(exc_type, value))
  231         if type(tblist) != list:
  232             tblist = [tblist]
  233         for line in tblist:
  234             log.critical('  %s\n' % line.rstrip())
  235         sys.exit(9)
  236 
  237 #######################################
  238 if __name__ == '__main__':
  239     main()