Exemplo n.º 1
0
    def do_read(self, arg):
        '''Read mail by uid.'''
        try:
            args = docopt.docopt(u'\n'.join([
                u'Usage: read [options] <mail_uid> [<save_directory>]',
                u'',
                u'Options:',
                u'    -b, --browser     Open mail in browser',
            ]), arg)
        except SystemExit:
            return

        fetched_mail = fetch.read(self.imap_account, args['<mail_uid>'],
                                  save_directory=args['<save_directory>'])
        if fetched_mail is None:
            log.error("Mail was not fetched, an error occured")

        if args['--browser'] is True:
            temp_file = tempfile.NamedTemporaryFile(delete=False)
            temp_file.write(fetch.display(fetched_mail,
                                          browser=True).encode('utf-8'))

            webbrowser.open_new_tab(temp_file.name)

            temp_file.close()
        else:
            sys.stdout.write(fetch.display(fetched_mail))
Exemplo n.º 2
0
    def do_read(self, arg):
        '''Read mail by uid.'''
        try:
            args = docopt.docopt(
                u'\n'.join([
                    u'Usage: read [options] <mail_uid> [<save_directory>]',
                    u'',
                    u'Options:',
                    u'    -b, --browser     Open mail in browser',
                ]), arg)
        except SystemExit:
            return

        fetched_mail = fetch.read(self.imap_account,
                                  args['<mail_uid>'],
                                  save_directory=args['<save_directory>'])
        if fetched_mail is None:
            log.error("Mail was not fetched, an error occured")

        if args['--browser'] is True:
            temp_file = tempfile.NamedTemporaryFile(delete=False)
            temp_file.write(
                fetch.display(fetched_mail, browser=True).encode('utf-8'))

            webbrowser.open_new_tab(temp_file.name)

            temp_file.close()
        else:
            sys.stdout.write(fetch.display(fetched_mail))
Exemplo n.º 3
0
    def test_read(self):
        self.imap_account = imaplib.IMAP4_SSL()
        mails = list(fetch.read(self.imap_account, 1, directory="INBOX"))

        for mail in mails:
            for header_name, header_value in mail['headers'].items():
                assert self.reference_mail['headers'][
                    header_name] == header_value
            assert len(mail['parts']) == len(self.reference_mail['parts'])
Exemplo n.º 4
0
    def test_read(self):
        self.imap_account = imaplib.IMAP4_SSL()
        mails = list(fetch.read(self.imap_account, 1, directory="INBOX"))

        for mail in mails:
            for header_name, header_value in mail['headers'].items():
                assert self.reference_mail['headers'][
                    header_name] == header_value
            assert len(mail['parts']) == len(self.reference_mail['parts'])
Exemplo n.º 5
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)
Exemplo n.º 6
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})
Exemplo n.º 7
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
        })
Exemplo n.º 8
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)
Exemplo n.º 9
0
def read(uid):
    '''Read mail by uid.'''
    ensure_connection()
    if isinstance(uid, six.string_types):
        uid = int(uid)
    fetched_mails = list(fetch.read(imap_account, uid))
    if fetched_mails is None:
        print "VIMAP: Mail was not fetched, an error occured"
        list_dir()

    global current_mail
    reset_buffer('vimap-read')
    b = vim.current.buffer
    b[:] = None
    for fetched_mail in fetched_mails:
        current_mail = fetched_mail
        for line in fetch.display(current_mail).split('\n'):
            b.append(line.replace('\r', ''))

    vim.command("set ft=mail")
    for key, action in read_mappings:
        vim.command("nnoremap <silent> <buffer> {} {}".format(key, action))
    vim.command("normal dd")