Example #1
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
Example #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
Example #3
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
Example #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
Example #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
Example #6
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
Example #7
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
Example #8
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
Example #9
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')
    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
Example #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,
    )

    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
Example #11
0
    def test_config_file_from_default_config_file(self):
        const.DEFAULT_CONFIG_FILE = 'config-example.ini'

        self.conf = config.new_context_from_file()

        if self.conf is not None:
            for key, value in config.DEFAULT_CONFIG.items():
                self.assertEqual(self.conf[key], value)
Example #12
0
    def test_config_file_from_non_existing_file(self):
        const.DEFAULT_CONFIG_FILE = 'config-imaginary-file.ini'

        self.conf = config.new_context_from_file()

        if self.conf is not None:
            for key, value in config.DEFAULT_CONFIG.items():
                assert self.conf[key] == value
Example #13
0
    def test_config_file_from_non_existing_file(self):
        const.DEFAULT_CONFIG_FILE = 'config-imaginary-file.ini'

        self.conf = config.new_context_from_file()

        if self.conf is not None:
            for key, value in config.DEFAULT_CONFIG.items():
                assert self.conf[key] == value
Example #14
0
    def test_config_file_from_default_config_file(self):
        const.DEFAULT_CONFIG_FILE = 'config-example.ini'

        self.conf = config.new_context_from_file()

        if self.conf is not None:
            for key, value in config.DEFAULT_CONFIG.items():
                self.assertEqual(self.conf[key], value)
Example #15
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]))
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.WARNING,
        stream=sys.stdout,
    )

    ctx = config.new_context_from_file(args['--config-file'])
    helpers.connect(ctx)
    flag(ctx, args['<mail_id>'], args['<flag>'], directory=args['<directory>'])
    return 0
Example #16
0
    def test_other_sasl_auth_with_initial_response(self):
        self.config_file.write('sasl_auth = OAUTHBEARER\n')
        self.config_file.write('sasl_ir = 12345abcde\n')
        self.config_file.seek(SEEK_SET, 0)

        self.conf = config.new_context_from_file(self.config_file.name,
                                                 section='imap')
        assert self.conf['hostname'] == 'imap.example.org'
        assert self.conf['username'] == 'username'
        assert self.conf['sasl_auth'] == 'OAUTHBEARER'
        assert self.conf['sasl_ir'] == '12345abcde'
Example #17
0
    def test_xoauth2_with_bearer_access_token(self):
        self.config_file.write('sasl_auth = XOAUTH2\n')
        self.config_file.write('bearer_access_token = 12345abcde\n')
        self.config_file.seek(SEEK_SET, 0)

        self.conf = config.new_context_from_file(self.config_file.name,
                                                 section='imap')
        assert self.conf['hostname'] == 'imap.example.org'
        assert self.conf['username'] == 'username'
        assert self.conf['sasl_auth'] == 'XOAUTH2'
        assert self.conf['sasl_ir'] == \
            'user=username\x01auth=Bearer 12345abcde\x01\x01'
Example #18
0
    def setUp(self):
        self.ctx = config.new_context_from_file('~/.config/imap-cli')

        imaplib.IMAP4_SSL = mock.Mock()
        imap_connection = imaplib.IMAP4_SSL('localhost')
        imap_connection.fetch = mock.Mock(return_value=('OK', [('1 (RFC822 {2323}', "EMAIL CONTENT"), ')']))
        imap_connection.list = mock.Mock(
            return_value=('OK', ['(\\HasNoChildren) "." "Directory_name"', '(\\HasNoChildren) "." "INBOX"'])
        )
        imap_connection.login = mock.Mock(return_value=('OK', ['Logged in']))
        imap_connection.select = mock.Mock(return_value=('OK', ['1']))
        imap_connection.status(return_value=('OK', ['"Directory_name" (MESSAGES 1 RECENT 1 UNSEEN 0)']))
Example #19
0
def main():
    args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]))
    logging.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.WARNING,
        stream=sys.stdout,
    )

    ctx = config.new_context_from_file(args['--config-file'])
    if args['--format'] is not None:
        ctx.format_status = args['--format']

    helpers.connect(ctx)
    sys.stdout.write(read(ctx, args['<mail_id>'], directory=args['<directory>']))
    return 0
Example #20
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
Example #21
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})
Example #22
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
        })
Example #23
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
Example #24
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
Example #25
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
Example #26
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
Example #27
0
import re
import sys
from wsgiref import simple_server

import six
from webob.dec import wsgify
from webob.exc import status_map

import imap_cli
from imap_cli import config
from imap_cli import const
from imap_cli import fetch
from imap_cli import search


conf = config.new_context_from_file(section="imap")
imap_account = None
log = logging.getLogger("Imap-CLI API")
routes = []


@wsgify
def read_controller(req):
    params = req.params
    inputs = {"directory": params.get("directory") or const.DEFAULT_DIRECTORY, "uid": req.urlvars.get("uid")}

    if inputs["uid"] is None:
        return "You need to specify an UID"

    imap_cli.change_dir(imap_account, inputs["directory"] or const.DEFAULT_DIRECTORY)
    fetched_mail = fetch.read(imap_account, inputs["uid"])
Example #28
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
Example #29
0

"""VIMAP python functions"""


import vim

import six

import imap_cli
from imap_cli import config
from imap_cli import fetch
from imap_cli import search


connect_conf = config.new_context_from_file(section='imap')
current_dir = 'INBOX'
current_mail = None
display_conf = {
    'format_list': u'{uid:>5} ▾ {from:<36.35} : {subject}',
    'format_status': u'▸ {directory}  - {count} ({unseen})',
    'format_thread': u'{uid:>5} ▾ {from:<36.35} : {subject}',
    'limit': 20}
imap_account = None
trash_conf = config.new_context_from_file(section='trash')
uids = []

status_mappings = [
    ('o', ':python vimap.list_dir(vim.current.line.split()[1])<cr>'),
    ('q', ':q<CR>'),
]
Example #30
0
    def test_config_file_from_example_config_file(self):
        config_example_filename = 'config-example.ini'
        self.conf = config.new_context_from_file(config_example_filename)

        for key, value in config.DEFAULT_CONFIG.items():
            assert self.conf[key] == value
Example #31
0
    def test_config_file_from_example_config_file(self):
        config_example_filename = 'config-example.ini'
        self.conf = config.new_context_from_file(config_example_filename)

        for key, value in config.DEFAULT_CONFIG.items():
            assert self.conf[key] == value
Example #32
0
import logging
import re
import sys
from wsgiref import simple_server

import six
from webob.dec import wsgify
from webob.exc import status_map

import imap_cli
from imap_cli import config
from imap_cli import const
from imap_cli import fetch
from imap_cli import search

conf = config.new_context_from_file(section='imap')
imap_account = None
log = logging.getLogger('Imap-CLI API')
routes = []


@wsgify
def read_controller(req):
    params = req.params
    inputs = {
        'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
        'uid': req.urlvars.get('uid'),
    }

    if inputs['uid'] is None:
        return 'You need to specify an UID'
Example #33
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