Пример #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
def fetch_uids(imap_account, charset=None, limit=None, search_criterion=None):
    """Retrieve information for every mail search_criterion.

    .. versionadded:: 0.3

    :param imap_account: imaplib.IMAP4 or imaplib.IMAP4_SSL instance
    :param charset: Desired charset for IMAP response
    :param limit: Return only last mails
    :param search_criterion: List of criteria for IMAP Search
    """
    request_search_criterion = search_criterion
    if search_criterion is None:
        request_search_criterion = 'ALL'
    elif isinstance(search_criterion, list):
        request_search_criterion = combine_search_criterion(search_criterion)

    if imap_account.state != 'SELECTED':
        log.warning(u'No directory specified, selecting {}'.format(
            const.DEFAULT_DIRECTORY))
        imap_cli.change_dir(imap_account, const.DEFAULT_DIRECTORY)

    status, data = imap_account.uid('SEARCH', charset,
                                    request_search_criterion)
    if status == const.STATUS_OK:
        return data[0].split() if limit is None else data[0].split()[-limit:]
Пример #3
0
def fetch_threads(imap_account, charset=None, limit=None,
                  search_criterion=None):
    """Retrieve information for every mail search_criterion by thread.

    .. versionadded:: 0.5

    :param imap_account: imaplib.IMAP4 or imaplib.IMAP4_SSL instance
    :param charset: Desired charset for IMAP response
    :param limit: Return only last mails
    :param search_criterion: List of criteria for IMAP Search
    """
    request_search_criterion = search_criterion
    if search_criterion is None or search_criterion == ['ALL']:
        request_search_criterion = 'ALL'
    if charset is None:
        charset = 'UTF-8'
    if isinstance(search_criterion, list):
        request_search_criterion = combine_search_criterion(search_criterion)

    if imap_account.state != 'SELECTED':
        log.warning(u'No directory specified, selecting {}'.format(
            const.DEFAULT_DIRECTORY))
        imap_cli.change_dir(imap_account, const.DEFAULT_DIRECTORY)

    status, data = imap_account.uid('THREAD', 'REFERENCES', charset,
                                    request_search_criterion)
    if status != const.STATUS_OK:
        return None
    threads = parse_thread_response(data[0])
    return threads if limit is None else threads[-limit:]
Пример #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,
    )

    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
Пример #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 fetch_uids(imap_account, charset=None, limit=None, search_criterion=None):
    """Retrieve information for every mail search_criterion.

    .. versionadded:: 0.3

    :param imap_account: imaplib.IMAP4 or imaplib.IMAP4_SSL instance
    :param charset: Desired charset for IMAP response
    :param limit: Return only last mails
    :param search_criterion: List of criteria for IMAP Search
    """
    request_search_criterion = search_criterion
    if search_criterion is None:
        request_search_criterion = 'ALL'
    elif isinstance(search_criterion, list):
        request_search_criterion = combine_search_criterion(search_criterion)

    if imap_account.state != 'SELECTED':
        log.warning(u'No directory specified, selecting {}'.format(
            const.DEFAULT_DIRECTORY))
        imap_cli.change_dir(imap_account, const.DEFAULT_DIRECTORY)

    status, data = imap_account.uid('SEARCH', charset,
                                    request_search_criterion)
    if status == const.STATUS_OK:
        return data[0].split() if limit is None else data[0].split()[-limit:]
Пример #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,
    )

    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
Пример #8
0
def fetch_threads(imap_account,
                  charset=None,
                  limit=None,
                  search_criterion=None):
    """Retrieve information for every mail search_criterion by thread.

    .. versionadded:: 0.5

    :param imap_account: imaplib.IMAP4 or imaplib.IMAP4_SSL instance
    :param charset: Desired charset for IMAP response
    :param limit: Return only last mails
    :param search_criterion: List of criteria for IMAP Search
    """
    request_search_criterion = search_criterion
    if search_criterion is None or search_criterion == ['ALL']:
        request_search_criterion = 'ALL'
    if charset is None:
        charset = 'UTF-8'
    if isinstance(search_criterion, list):
        request_search_criterion = combine_search_criterion(search_criterion)

    if imap_account.state != 'SELECTED':
        log.warning(u'No directory specified, selecting {}'.format(
            const.DEFAULT_DIRECTORY))
        imap_cli.change_dir(imap_account, const.DEFAULT_DIRECTORY)

    status, data = imap_account.uid('THREAD', 'REFERENCES', charset,
                                    request_search_criterion)
    if status != const.STATUS_OK:
        return None
    threads = parse_thread_response(data[0])
    return threads if limit is None else threads[-limit:]
Пример #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
Пример #10
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
Пример #11
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
Пример #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():
    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
Пример #14
0
def search_controller(req):
    params = req.params
    inputs = {
        "directory": params.get("directory") or const.DEFAULT_DIRECTORY,
        "tags": params.getall("tag") or None,
        "text": params.get("text") or None,
    }

    imap_cli.change_dir(imap_account, inputs["directory"])

    search_criterion = search.create_search_criterion(tags=inputs["tags"], text=inputs["text"])
    mail_set = search.fetch_uids(imap_account, search_criterion=search_criterion or [])
    mails_info = list(search.fetch_mails_info(imap_account, mail_set=mail_set))
    return json.dumps(mails_info, indent=2)
Пример #15
0
def search_controller(req):
    params = req.params
    inputs = {
        'directory': params.get('directory') or const.DEFAULT_DIRECTORY,
        'tags': params.getall('tag') or None,
        'text': params.get('text') or None,
    }

    imap_cli.change_dir(imap_account, inputs['directory'])

    search_criterion = search.create_search_criterion(tags=inputs['tags'],
                                                      text=inputs['text'])
    mail_set = search.fetch_uids(imap_account,
                                 search_criterion=search_criterion or [])
    mails_info = list(search.fetch_mails_info(imap_account, mail_set=mail_set))
    return json.dumps(mails_info, indent=2)
Пример #16
0
def fetch(imap_account, message_set=None, message_parts=None):
    """Return mails corresponding to mails_id.

    Keyword arguments:
    message_set     -- Iterable containing mails ID (integers)
    message_parts   -- Iterable of message part names or IMAP protocoles
                       ENVELOP string

    Available message_parts are listed in const.MESSAGE_PARTS, for more
    information checkout RFC3501
    """
    if message_set is None or not isinstance(message_set,
                                             collections.Iterable):
        if isinstance(message_set, int):
            message_set = [str(message_set)]
        else:
            log.error('Can\'t fetch email {}'.format(message_set))
            return None
    if len(message_set) == 0:
        log.error('No uid given')
        return None
    if message_parts is None:
        message_parts = ['RFC822']

    request_message_set = ','.join(str(mail_id) for mail_id in message_set)
    request_message_parts = '({})'.format(' '.join(message_parts)
                                          if isinstance(message_parts,
                                                        collections.Iterable)
                                          else message_parts)
    if imap_account.state != 'SELECTED':
        log.warning(u'No directory specified, selecting {}'.format(
            const.DEFAULT_DIRECTORY))
        imap_cli.change_dir(imap_account, const.DEFAULT_DIRECTORY)
    typ, data_bytes = imap_account.uid(
        'FETCH',
        request_message_set, request_message_parts)
    data = []
    for mail in data_bytes:
        if len(mail) == 1:
            continue
        mail_parts = []
        for mail_part in mail:
            mail_parts.append(mail_part.decode('utf-8'))
        data.append(mail_parts)

    if typ == const.STATUS_OK:
        return data
Пример #17
0
def fetch(imap_account, message_set=None, message_parts=None):
    """Return mails corresponding to mails_id.

    Keyword arguments:
    message_set     -- Iterable containing mails ID (integers)
    message_parts   -- Iterable of message part names or IMAP protocoles
                       ENVELOP string

    Available message_parts are listed in const.MESSAGE_PARTS, for more
    information checkout RFC3501
    """
    if message_set is None or not isinstance(message_set,
                                             collections.Iterable):
        if isinstance(message_set, int):
            message_set = [str(message_set)]
        else:
            log.error('Can\'t fetch email {}'.format(message_set))
            return None
    if len(message_set) == 0:
        log.error('No uid given')
        return None
    if message_parts is None:
        message_parts = ['RFC822']

    request_message_set = ','.join(str(mail_id) for mail_id in message_set)
    request_message_parts = '({})'.format(
        ' '.join(message_parts) if isinstance(message_parts, collections.
                                              Iterable) else message_parts)
    if imap_account.state != 'SELECTED':
        log.warning(u'No directory specified, selecting {}'.format(
            const.DEFAULT_DIRECTORY))
        imap_cli.change_dir(imap_account, const.DEFAULT_DIRECTORY)
    typ, data_bytes = imap_account.uid('FETCH', request_message_set,
                                       request_message_parts)
    data = []
    for mail in data_bytes:
        if len(mail) == 1:
            continue
        mail_parts = []
        for mail_part in mail:
            mail_parts.append(mail_part.decode('utf-8'))
        data.append(mail_parts)

    if typ == const.STATUS_OK:
        return data
Пример #18
0
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"])
    if fetched_mail is None:
        # TODO(rsoufflet) Handle this error with HTTP
        return "Mail was not fetched, an error occured"

    return_json = copy.deepcopy(fetched_mail)
    for part in return_json["parts"]:
        if not part["content_type"].startswith("text"):
            del part["data"]
    return json.dumps(return_json, indent=2)
Пример #19
0
def change_mailbox(mailbox_name):
    '''Change selected IMAP folder.'''
    global current_dir
    ensure_connection()
    cd_result = imap_cli.change_dir(imap_account, directory=mailbox_name)
    if cd_result == -1:
        print 'VIMAP: IMAP Folder {} can\'t be found'.format(mailbox_name)
        return None
    current_dir = mailbox_name
    return mailbox_name
Пример #20
0
    def do_cd(self, arg):
        '''Change selected IMAP folder.'''
        try:
            args = docopt.docopt('Usage: cd <directory>', arg)
        except SystemExit:
            return

        cd_result = imap_cli.change_dir(self.imap_account,
                                        directory=args['<directory>'])
        if cd_result == -1:
            sys.stdout.write('IMAP Folder can\'t be found\n')
        else:
            self.prompt = '(imap-cli "{}") '.format(args['<directory>'])
Пример #21
0
    def do_cd(self, arg):
        '''Change selected IMAP folder.'''
        try:
            args = docopt.docopt('Usage: cd <directory>', arg)
        except SystemExit:
            return

        cd_result = imap_cli.change_dir(self.imap_account,
                                        directory=args['<directory>'])
        if cd_result == -1:
            sys.stdout.write('IMAP Folder can\'t be found\n')
        else:
            self.prompt = '(imap-cli "{}") '.format(args['<directory>'])
Пример #22
0
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'])
    if fetched_mail is None:
        # TODO(rsoufflet) Handle this error with HTTP
        return 'Mail was not fetched, an error occured'

    return_json = copy.deepcopy(fetched_mail)
    for part in return_json['parts']:
        if not part['content_type'].startswith('text'):
            del part['data']
    return json.dumps(return_json, indent=2)
Пример #23
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
Пример #24
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
Пример #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)

    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
Пример #26
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})
Пример #27
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
        })
Пример #28
0
    def test_change_dir_twice(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        assert imap_cli.change_dir(self.imap_account, 'Test') == '1'
        assert imap_cli.change_dir(self.imap_account, 'INBOX') == '1'
Пример #29
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
Пример #30
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
Пример #31
0
    def test_wrong_change_dir(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        assert imap_cli.change_dir(self.imap_account, 'NotADirectory') == -1
Пример #32
0
    def test_change_dir(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        imap_cli.change_dir(self.imap_account, 'Test')
Пример #33
0
    def test_change_dir(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        imap_cli.change_dir(self.imap_account, 'Test')
Пример #34
0
    def test_change_dir_twice(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        assert imap_cli.change_dir(self.imap_account, 'Test') == '1'
        assert imap_cli.change_dir(self.imap_account, 'INBOX') == '1'
Пример #35
0
    def test_wrong_change_dir(self):
        self.imap_account = imaplib.IMAP4_SSL()
        self.imap_account.login()

        assert imap_cli.change_dir(self.imap_account, 'NotADirectory') == -1