예제 #1
0
    def test_disconnect_selected_state(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        imap_cli.change_dir(self.imap_account, 'Test')
        imap_cli.disconnect(self.imap_account)
        assert self.imap_account.state == 'LOGOUT'
예제 #2
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
예제 #3
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
예제 #4
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
예제 #5
0
    def test_disconnect_selected_state(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        imap_cli.change_dir(self.imap_account, 'Test')
        imap_cli.disconnect(self.imap_account)
        assert self.imap_account.state == 'LOGOUT'
예제 #6
0
 def do_quit(self, arg):
     'Exit this shell'
     global keep_alive_bool
     keep_alive_bool = False
     imap_cli.disconnect(self.imap_account)
     sys.stdout.write('Bye\n')
     return True
예제 #7
0
 def do_quit(self, arg):
     'Exit this shell'
     global keep_alive_bool
     keep_alive_bool = False
     imap_cli.disconnect(self.imap_account)
     sys.stdout.write('Bye\n')
     return True
예제 #8
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
예제 #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,
    )

    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
예제 #10
0
파일: list_mail.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,
    )

    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
예제 #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
파일: 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})
예제 #13
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
        })
예제 #14
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
예제 #15
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
예제 #16
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
예제 #17
0
    def test_disconnect(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        imap_cli.disconnect(self.imap_account)
        assert self.imap_account.state == 'LOGOUT'
예제 #18
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
예제 #19
0
    def test_disconnect(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        imap_cli.disconnect(self.imap_account)
        assert self.imap_account.state == 'LOGOUT'
예제 #20
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