示例#1
0
文件: flag.py 项目: sweth/imap-cli
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    conf = config.new_context_from_file(args['--config-file'], section='imap')
    if conf is None:
        return 1

    try:
        imap_account = imap_cli.connect(**conf)
        imap_cli.change_dir(imap_account,
                            args['--directory'] or const.DEFAULT_DIRECTORY,
                            read_only=False)

        flag(imap_account, [args['<mail_id>']],
             args['<flag>'],
             unset=args['--unset'])

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#2
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='increase output verbosity')

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.WARNING,
        stream=sys.stdout,
    )

    connection_config = config.new_context_from_file(section='imap')
    if connection_config is None:
        return 1
    delete_config = config.new_context_from_file(section='trash')

    imap_account = imap_cli.connect(**connection_config)
    imap_shell = ImapShell(imap_account)
    imap_shell.delete_conf = delete_config
    keep_alive_thread = threading.Thread(target=keep_alive,
                                         args=(imap_account,))

    keep_alive_thread.start()
    imap_shell.cmdloop()
    keep_alive_thread.join()

    return 0
示例#3
0
def main():
    global imap_account
    global routes

    if conf is None:
        return 1
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    for routing in routings:
        methods, regex, app = routing[:3]
        if isinstance(methods, six.string_types):
            methods = (methods, )
        vars = routing[3] if len(routing) >= 4 else {}
        routes.append((methods, re.compile(regex), app, vars))
        log.info('Route {} openned'.format(regex[1:-1]))

    try:
        imap_account = imap_cli.connect(**conf)

        httpd = simple_server.make_server('127.0.0.1', 8000, router)
        log.info('Serving on http://127.0.0.1:8000')
        httpd.serve_forever()
    except KeyboardInterrupt:
        log.info('Interupt by user, exiting')

    return 0
示例#4
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    try:
        connect_conf = config.new_context_from_file(args['--config-file'],
                                                    section='imap')
        if connect_conf is None:
            return 1
        display_conf = config.new_context_from_file(args['--config-file'],
                                                    section='display')
        if args['--format'] is not None:
            display_conf['format_status'] = six.text_type(args['--format'])

        imap_account = imap_cli.connect(**connect_conf)
        for directory_status in sorted(imap_cli.status(imap_account),
                                       key=lambda obj: obj['directory']):
            sys.stdout.write(
                display_conf['format_status'].format(**directory_status))
            sys.stdout.write('\n')
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#5
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    conf = config.new_context_from_file(args['--config-file'], section='imap')
    delete_conf = config.new_context_from_file(args['--config-file'],
                                               section='trash')
    if conf is None:
        return 1

    try:
        imap_account = imap_cli.connect(**conf)
        imap_cli.change_dir(imap_account,
                            args['--directory'] or const.DEFAULT_DIRECTORY,
                            read_only=False)

        if delete_conf['delete_method'] == 'MOVE_TO_TRASH':
            copy.copy(imap_account, args['<mail_id>'],
                      delete_conf['trash_directory'])
        flag.flag(imap_account, args['<mail_id>'], [const.FLAG_DELETED])
        if delete_conf['delete_method'] in ['MOVE_TO_TRASH', 'EXPUNGE']:
            imap_account.expunge()

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#6
0
def main():
    global imap_account
    global routes

    if conf is None:
        return 1
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    for routing in routings:
        methods, regex, app = routing[:3]
        if isinstance(methods, six.string_types):
            methods = (methods,)
        vars = routing[3] if len(routing) >= 4 else {}
        routes.append((methods, re.compile(regex), app, vars))
        log.info("Route {} openned".format(regex[1:-1]))

    try:
        imap_account = imap_cli.connect(**conf)

        httpd = simple_server.make_server("127.0.0.1", 8000, router)
        log.info("Serving on http://127.0.0.1:8000")
        httpd.serve_forever()
    except KeyboardInterrupt:
        log.info("Interupt by user, exiting")

    return 0
示例#7
0
文件: vimap.py 项目: Gentux/vimap
def ensure_connection():
    global imap_account
    try:
        imap_account.noop()
    except Exception as e:
        print e
        imap_account = imap_cli.connect(**connect_conf)
示例#8
0
文件: copy.py 项目: Gentux/imap-cli
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    conf = config.new_context_from_file(args['--config-file'], section='imap')
    if conf is None:
        return 1

    try:
        imap_account = imap_cli.connect(**conf)
        imap_cli.change_dir(imap_account,
                            args['--from'] or const.DEFAULT_DIRECTORY,
                            read_only=False)

        copy(imap_account, args['<mail_id>'], args['<dest>'])
        if args['--delete']:
            flag.flag(imap_account, args['<mail_id>'], [const.FLAG_DELETED])
            imap_account.expunge()

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#9
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='increase output verbosity')

    args = parser.parse_args()

    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.WARNING,
        stream=sys.stdout,
    )

    connection_config = config.new_context_from_file(section='imap')
    if connection_config is None:
        return 1
    delete_config = config.new_context_from_file(section='trash')

    imap_account = imap_cli.connect(**connection_config)
    imap_shell = ImapShell(imap_account)
    imap_shell.delete_conf = delete_config
    keep_alive_thread = threading.Thread(target=keep_alive,
                                         args=(imap_account, ))

    keep_alive_thread.start()
    imap_shell.cmdloop()
    keep_alive_thread.join()

    return 0
示例#10
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    try:
        connect_conf = config.new_context_from_file(args['--config-file'],
                                                    section='imap')
        if connect_conf is None:
            return 1
        display_conf = config.new_context_from_file(args['--config-file'],
                                                    section='display')
        if args['--format'] is not None:
            display_conf['format_status'] = six.text_type(args['--format'])

        imap_account = imap_cli.connect(**connect_conf)
        for directory_status in sorted(imap_cli.status(imap_account),
                                       key=lambda obj: obj['directory']):
            sys.stdout.write(
                display_conf['format_status'].format(**directory_status))
            sys.stdout.write('\n')
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#11
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('imap_server', help="IMAP Server hostname")
    parser.add_argument('searched_address', help="Searched address")
    parser.add_argument('-l', '--login', help="Login for IMAP account")
    parser.add_argument('--no-ssl', action='store_true', help="Don't use SSL")
    parser.add_argument('-v',
                        '--verbose',
                        action='store_true',
                        help='increase output verbosity')

    args = parser.parse_args()
    password = getpass.getpass()

    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    try:
        imap_account = imap_cli.connect(
            hostname=args.imap_server,
            username=args.login,
            password=password,
            ssl=not args.no_ssl,
        )
        for directory_status in sorted(imap_cli.status(imap_account),
                                       key=lambda obj: obj['directory']):
            imap_cli.change_dir(imap_account, directory_status['directory'])

            mail_set = search.fetch_uids(
                imap_account,
                search_criterion=[
                    search.create_search_criterion_by_mail_address(
                        args.searched_address)
                ],
            )

            if len(mail_set) > 0:
                sys.stdout.write(u'{} Directory\n'.format(
                    directory_status['directory']))

                for mail_info in search.fetch_mails_info(imap_account,
                                                         mail_set=mail_set):
                    format_string = u''.join([
                        u'    {:<10} ', u'From : {:<30.30} \t',
                        u'Subject : {:.50}\n'
                    ])
                    sys.stdout.write(
                        format_string.format(mail_info['uid'],
                                             mail_info['from'],
                                             mail_info['subject']))
        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#12
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    connect_conf = config.new_context_from_file(args['--config-file'],
                                                section='imap')
    if connect_conf is None:
        return 1
    display_conf = config.new_context_from_file(args['--config-file'],
                                                section='display')
    if args['--format'] is not None:
        config_key = 'format_thread' if args['--thread'] else 'format_list'
        display_conf[config_key] = args['--format']
    if args['--limit'] is not None:
        try:
            limit = int(args['--limit'])
            if limit < 1:
                raise ValueError
        except ValueError:
            log.error('Invalid argument limit : {}'.format(args['--limit']))
            return 1
    else:
        limit = None

    try:
        imap_account = imap_cli.connect(**connect_conf)
        imap_cli.change_dir(
            imap_account,
            directory=args['<directory>'] or const.DEFAULT_DIRECTORY)
        if args['--thread'] is False:
            for mail_info in search.fetch_mails_info(imap_account,
                                                     limit=limit):
                sys.stdout.write(
                    display_conf['format_list'].format(**mail_info))
                sys.stdout.write('\n')
        else:
            threads = search.fetch_threads(imap_account, limit=limit)
            mail_tree = search.threads_to_mail_tree(threads)
            for output in search.display_mail_tree(
                    imap_account,
                    mail_tree,
                    format_thread=display_conf['format_thread']):
                sys.stdout.write(output)
                sys.stdout.write('\n')
        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#13
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    connect_conf = config.new_context_from_file(args['--config-file'],
                                                section='imap')
    if connect_conf is None:
        return 1
    display_conf = config.new_context_from_file(args['--config-file'],
                                                section='display')
    if args['--format'] is not None:
        config_key = 'format_thread' if args['--thread'] else 'format_list'
        display_conf[config_key] = args['--format']
    if args['--limit'] is not None:
        try:
            limit = int(args['--limit'])
            if limit < 1:
                raise ValueError
        except ValueError:
            log.error('Invalid argument limit : {}'.format(args['--limit']))
            return 1
    else:
        limit = None

    try:
        imap_account = imap_cli.connect(**connect_conf)
        imap_cli.change_dir(imap_account,
                            directory=args['<directory>']
                            or const.DEFAULT_DIRECTORY)
        if args['--thread'] is False:
            for mail_info in search.fetch_mails_info(imap_account,
                                                     limit=limit):
                sys.stdout.write(
                    display_conf['format_list'].format(**mail_info))
                sys.stdout.write('\n')
        else:
            threads = search.fetch_threads(imap_account, limit=limit)
            mail_tree = search.threads_to_mail_tree(threads)
            for output in search.display_mail_tree(
                    imap_account,
                    mail_tree,
                    format_thread=display_conf['format_thread']):
                sys.stdout.write(output)
                sys.stdout.write('\n')
        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#14
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('imap_server', help="IMAP Server hostname")
    parser.add_argument('searched_address', help="Searched address")
    parser.add_argument('-l', '--login', help="Login for IMAP account")
    parser.add_argument('--no-ssl', action='store_true', help="Don't use SSL")
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='increase output verbosity')

    args = parser.parse_args()
    password = getpass.getpass()

    logging.basicConfig(level=logging.INFO, stream=sys.stdout)

    try:
        imap_account = imap_cli.connect(
            hostname=args.imap_server,
            username=args.login,
            password=password,
            ssl=not args.no_ssl,
        )
        for directory_status in sorted(imap_cli.status(imap_account),
                                       key=lambda obj: obj['directory']):
            imap_cli.change_dir(imap_account, directory_status['directory'])

            mail_set = search.fetch_uids(
                imap_account,
                search_criterion=[
                    search.create_search_criterion_by_mail_address(
                        args.searched_address)],
            )

            if len(mail_set) > 0:
                sys.stdout.write(u'{} Directory\n'.format(
                    directory_status['directory']))

                for mail_info in search.fetch_mails_info(imap_account,
                                                         mail_set=mail_set):
                    format_string = u''.join([
                        u'    {:<10} ',
                        u'From : {:<30.30} \t',
                        u'Subject : {:.50}\n'])
                    sys.stdout.write(format_string.format(
                        mail_info['uid'],
                        mail_info['from'],
                        mail_info['subject']))
        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#15
0
文件: views.py 项目: arnpi/PyNews
def mail_view(request):
    user = check_user_logged(request)
    if user is False:
        return dict(
            feed= "not logged",
            project= 'PyNews'
        )
    user = get_user_by_username(user)
    result = []
    mail_params = DBSession.query(Mail).filter_by(user=user)
    resultat = mail_params.all()
    for el in resultat:
        pprint(el.hostname)

        config_file = 'config-email.ini'
        connect_conf = config.new_context_from_file(config_file, section='imap')
        connect_conf['hostname'] = el.hostname
        connect_conf['password'] = el.password
        connect_conf['username'] = el.username
        connect_conf['ssl'] = el.ssl
        connect_conf['port'] = el.port
        try:
            imap_account =  imap_cli.connect(**connect_conf)
        except Exception, e:
            return dict(
                mails= ["Error while connecting to imap server"],
                project= 'PyNews'
            )

        print "#"*10
        count = int(imap_cli.change_dir(imap_account, 'INBOX')[0]) + 10
        response = []
        for ite in xrange(count -10, count):
            mail_response = dict()
            mail = fetch.read(imap_account, ite, directory="INBOX")
            mail_response['from'] = mail['headers']['From']
            mail_response['to'] = mail['headers']['To']
            mail_response['date'] = mail['headers']['Date']
            mail_response['subject'] = mail['headers']['Subject']
            mail_response['parts'] = mail['parts'][0]['as_string']
            response.append(mail_response)
        imap_cli.disconnect(imap_account)
        result.append({"mail_user": connect_conf['username'], "mail_box": response})
示例#16
0
def mail_view(request):
    user = check_user_logged(request)
    if user is False:
        return dict(feed="not logged", project='PyNews')
    user = get_user_by_username(user)
    result = []
    mail_params = DBSession.query(Mail).filter_by(user=user)
    resultat = mail_params.all()
    for el in resultat:
        pprint(el.hostname)

        config_file = 'config-email.ini'
        connect_conf = config.new_context_from_file(config_file,
                                                    section='imap')
        connect_conf['hostname'] = el.hostname
        connect_conf['password'] = el.password
        connect_conf['username'] = el.username
        connect_conf['ssl'] = el.ssl
        connect_conf['port'] = el.port
        try:
            imap_account = imap_cli.connect(**connect_conf)
        except Exception, e:
            return dict(mails=["Error while connecting to imap server"],
                        project='PyNews')

        print "#" * 10
        count = int(imap_cli.change_dir(imap_account, 'INBOX')[0]) + 10
        response = []
        for ite in xrange(count - 10, count):
            mail_response = dict()
            mail = fetch.read(imap_account, ite, directory="INBOX")
            mail_response['from'] = mail['headers']['From']
            mail_response['to'] = mail['headers']['To']
            mail_response['date'] = mail['headers']['Date']
            mail_response['subject'] = mail['headers']['Subject']
            mail_response['parts'] = mail['parts'][0]['as_string']
            response.append(mail_response)
        imap_cli.disconnect(imap_account)
        result.append({
            "mail_user": connect_conf['username'],
            "mail_box": response
        })
示例#17
0
def main():
    args = docopt.docopt('\n'.join(usage.split('\n')))

    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.WARNING,
        stream=sys.stdout,
    )
    pynotify.init(app_name)

    connection_config = config.new_context_from_file(args['--config-file'],
                                                     section='imap')
    if connection_config is None:
        return 1
    try:
        delay = int(args['--delay'] or 60)
    except ValueError:
        log.error('Wrong value for options "delay"')
        return 1
    format_str = args['--format'] or u' '.join([
        u'{recent:<3} new mails in ',
        u'{directory} ({count} total)'])

    imap_account = imap_cli.connect(**connection_config)

    time_count = 0
    sys.stdout.write('\n')
    while True:
        time_count += 1
        if time_count % delay == 0:
            notifications = []
            for status in imap_cli.status(imap_account):
                if (status['directory'] in args['<directories>'] and
                        status['recent'] != '0'):
                    notifications.append(format_str.format(**status))
            if len(notifications) > 0:
                notifier = pynotify.Notification("IMAP Notify",
                                                 u'\n'.join(notifications))
                notifier.show()
        time.sleep(1)

    return 0
示例#18
0
def main():
    args = docopt.docopt('\n'.join(usage.split('\n')))

    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.WARNING,
        stream=sys.stdout,
    )
    pynotify.init(app_name)

    connection_config = config.new_context_from_file(args['--config-file'],
                                                     section='imap')
    if connection_config is None:
        return 1
    try:
        delay = int(args['--delay'] or 60)
    except ValueError:
        log.error('Wrong value for options "delay"')
        return 1
    format_str = args['--format'] or u' '.join(
        [u'{recent:<3} new mails in ', u'{directory} ({count} total)'])

    imap_account = imap_cli.connect(**connection_config)

    time_count = 0
    sys.stdout.write('\n')
    while True:
        time_count += 1
        if time_count % delay == 0:
            notifications = []
            for status in imap_cli.status(imap_account):
                if (status['directory'] in args['<directories>']
                        and status['recent'] != '0'):
                    notifications.append(format_str.format(**status))
            if len(notifications) > 0:
                notifier = pynotify.Notification("IMAP Notify",
                                                 u'\n'.join(notifications))
                notifier.show()
        time.sleep(1)

    return 0
示例#19
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    if len(args['<mail_uid>']) == 0:
        args['<mail_uid>'] = sys.stdin.read().strip().split()
    if len(args['<mail_uid>']) == 0:
        sys.stderr.write('\n'.join(__doc__.split('\n')[2:]))
        return 1

    conf = config.new_context_from_file(args['--config-file'], section='imap')
    if conf is None:
        return 1

    try:
        imap_account = imap_cli.connect(**conf)
        imap_cli.change_dir(imap_account, args['--directory']
                            or const.DEFAULT_DIRECTORY)
        fetched_mails = read(imap_account,
                             args['<mail_uid>'],
                             save_directory=args['--save'])
        if fetched_mails is None:
            log.error("Mail was not fetched, an error occured")
            return 1

        for fetched_mail in fetched_mails:
            sys.stdout.write(display(fetched_mail))

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#20
0
文件: fetch.py 项目: Gentux/imap-cli
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
                         version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    if len(args['<mail_uid>']) == 0:
        args['<mail_uid>'] = sys.stdin.read().strip().split()
    if len(args['<mail_uid>']) == 0:
        sys.stderr.write('\n'.join(__doc__.split('\n')[2:]))
        return 1

    conf = config.new_context_from_file(args['--config-file'], section='imap')
    if conf is None:
        return 1

    try:
        imap_account = imap_cli.connect(**conf)
        imap_cli.change_dir(imap_account,
                            args['--directory'] or const.DEFAULT_DIRECTORY)
        fetched_mails = read(imap_account,
                             args['<mail_uid>'],
                             save_directory=args['--save'])
        if fetched_mails is None:
            log.error("Mail was not fetched, an error occured")
            return 1

        for fetched_mail in fetched_mails:
            sys.stdout.write(display(fetched_mail))

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#21
0
文件: delete.py 项目: Gentux/imap-cli
def main():
    args = docopt.docopt("\n".join(__doc__.split("\n")[2:]), version=const.VERSION)
    logging.basicConfig(level=logging.DEBUG if args["--verbose"] else logging.INFO, stream=sys.stdout)

    conf = config.new_context_from_file(args["--config-file"], section="imap")
    delete_conf = config.new_context_from_file(args["--config-file"], section="trash")
    if conf is None:
        return 1

    try:
        imap_account = imap_cli.connect(**conf)
        imap_cli.change_dir(imap_account, args["--directory"] or const.DEFAULT_DIRECTORY, read_only=False)

        if delete_conf["delete_method"] == "MOVE_TO_TRASH":
            copy.copy(imap_account, args["<mail_id>"], delete_conf["trash_directory"])
        flag.flag(imap_account, args["<mail_id>"], [const.FLAG_DELETED])
        if delete_conf["delete_method"] in ["MOVE_TO_TRASH", "EXPUNGE"]:
            imap_account.expunge()

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info("Interrupt by user, exiting")

    return 0
示例#22
0
 def test_connect_sasl_auth(self):
     self.imap_account = imap_cli.connect('hostname', 'username',
                                          sasl_auth='XOAUTH2',
                                          sasl_ir='12345abcde')
     assert isinstance(self.imap_account, tests.ImapConnectionMock)
示例#23
0
def main():
    args = docopt.docopt('\n'.join(usage.split('\n')), version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    connect_conf = config.new_context_from_file(args['--config-file'],
                                                section='imap')
    if connect_conf is None:
        return 1
    display_conf = config.new_context_from_file(args['--config-file'],
                                                section='display')
    if args['--format'] is not None:
        display_conf_key = ('format_thread'
                            if args['--thread'] is True
                            else 'format_list')
        display_conf[display_conf_key] = args['--format']
    if args.get('--tags') is not None:
        args['--tags'] = args['--tags'].split(',')
    if args['--date'] is not None:
        try:
            date = datetime.datetime.strptime(args['--date'], '%Y-%m-%d')
        except ValueError:
            date = None
    else:
        date = None
    if args['--limit'] is not None:
        try:
            limit = int(args['--limit'])
            if limit < 1:
                raise ValueError
        except ValueError:
            log.error('Invalid argument limit : {}'.format(args['--limit']))
            return 1
    else:
        limit = None

    try:
        imap_account = imap_cli.connect(**connect_conf)
        imap_cli.change_dir(
            imap_account,
            directory=args['<directory>'] or const.DEFAULT_DIRECTORY)
        search_criterion = create_search_criterion(
            address=args['--address'],
            date=date,
            subject=args['--subject'],
            size=args['--size'],
            tags=args['--tags'],
            text=args['--full-text'],
        )
        if args['--thread'] is False:
            mail_set = fetch_uids(imap_account,
                                  search_criterion=search_criterion)
            if len(mail_set) == 0:
                log.error('No mail found')
                return 0
            for mail_info in fetch_mails_info(imap_account,
                                              limit=limit, mail_set=mail_set):
                sys.stdout.write(
                    display_conf['format_list'].format(**mail_info))
                sys.stdout.write('\n')
        else:
            threads = fetch_threads(imap_account, limit=limit,
                                    search_criterion=search_criterion)
            mail_tree = threads_to_mail_tree(threads)
            for output in display_mail_tree(
                    imap_account, mail_tree,
                    format_thread=display_conf['format_thread']):
                sys.stdout.write(output)
                sys.stdout.write('\n')

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0
示例#24
0
 def test_connect_sasl_auth(self):
     self.imap_account = imap_cli.connect('hostname',
                                          'username',
                                          sasl_auth='XOAUTH2',
                                          sasl_ir='12345abcde')
     assert isinstance(self.imap_account, tests.ImapConnectionMock)
示例#25
0
 def test_connect_no_ssl(self):
     self.imap_account = imap_cli.connect('hostname',
                                          'username',
                                          'password',
                                          ssl=False)
     assert isinstance(self.imap_account, tests.ImapConnectionMock)
示例#26
0
 def test_connect_no_ssl(self):
     self.imap_account = imap_cli.connect('hostname', 'username',
                                          'password', ssl=False)
     assert isinstance(self.imap_account, tests.ImapConnectionMock)
示例#27
0
def main():
    args = docopt.docopt('\n'.join(usage.split('\n')), version=const.VERSION)
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        stream=sys.stdout,
    )

    connect_conf = config.new_context_from_file(args['--config-file'],
                                                section='imap')
    if connect_conf is None:
        return 1
    display_conf = config.new_context_from_file(args['--config-file'],
                                                section='display')
    if args['--format'] is not None:
        display_conf_key = ('format_thread'
                            if args['--thread'] is True else 'format_list')
        display_conf[display_conf_key] = args['--format']
    if args.get('--tags') is not None:
        args['--tags'] = args['--tags'].split(',')
    if args['--date'] is not None:
        try:
            date = datetime.datetime.strptime(args['--date'], '%Y-%m-%d')
        except ValueError:
            date = None
    else:
        date = None
    if args['--limit'] is not None:
        try:
            limit = int(args['--limit'])
            if limit < 1:
                raise ValueError
        except ValueError:
            log.error('Invalid argument limit : {}'.format(args['--limit']))
            return 1
    else:
        limit = None

    try:
        imap_account = imap_cli.connect(**connect_conf)
        imap_cli.change_dir(imap_account,
                            directory=args['<directory>']
                            or const.DEFAULT_DIRECTORY)
        search_criterion = create_search_criterion(
            address=args['--address'],
            date=date,
            subject=args['--subject'],
            size=args['--size'],
            tags=args['--tags'],
            text=args['--full-text'],
        )
        if args['--thread'] is False:
            mail_set = fetch_uids(imap_account,
                                  search_criterion=search_criterion)
            if len(mail_set) == 0:
                log.error('No mail found')
                return 0
            for mail_info in fetch_mails_info(imap_account,
                                              limit=limit,
                                              mail_set=mail_set):
                sys.stdout.write(
                    display_conf['format_list'].format(**mail_info))
                sys.stdout.write('\n')
        else:
            threads = fetch_threads(imap_account,
                                    limit=limit,
                                    search_criterion=search_criterion)
            mail_tree = threads_to_mail_tree(threads)
            for output in display_mail_tree(
                    imap_account,
                    mail_tree,
                    format_thread=display_conf['format_thread']):
                sys.stdout.write(output)
                sys.stdout.write('\n')

        imap_cli.disconnect(imap_account)
    except KeyboardInterrupt:
        log.info('Interrupt by user, exiting')

    return 0