Exemplo n.º 1
0
    def teardown_class(self):
        time.sleep(2)

        res_attr = conf.get('cyrus-sasl', 'result_attribute')

        exec("ac_folders = %s" % (conf.get_raw(conf.get('kolab', 'primary_domain'), 'autocreate_folders')))
        expected_number_of_folders = len(ac_folders.keys()) + 1

        users = []

        result = wap_client.users_list()
        for user in result['list'].keys():
            user_info = wap_client.user_info(user)
            users.append(user_info)
            result = wap_client.user_delete({'user': user})

        imap = IMAP()
        imap.connect()

        for user in users:
            if len(user[res_attr].split('@')) > 1:
                localpart = user[res_attr].split('@')[0]
                domain = user[res_attr].split('@')[1]

            folders = []
            folders.extend(imap.lm('user/%s' % (user[res_attr])))
            folders.extend(imap.lm('user/%s/*@%s' % (localpart,domain)))
Exemplo n.º 2
0
def execute(*args, **kw):
    """
        List deleted mailboxes
    """

    try:
        domain = conf.cli_args.pop(0)
    except:
        domain = utils.ask_question(_("Domain"))

    imap = IMAP()
    imap.connect()

    auth = Auth()
    auth.connect()

    domains = auth.list_domains()

    folders = []
    for primary,secondaries in domains:
        if not domain == primary and not domain in secondaries:
            continue

        folders.extend(imap.lm("user/%%@%s" % (primary)))
        for secondary in secondaries:
            folders.extend(imap.lm("user/%%@%s" % (secondary)))

    print "Deleted folders:"

    for folder in folders:
        if not conf.raw:
            print imap_utf7.decode(folder)
        else:
            print folder
Exemplo n.º 3
0
    def test_001_two_johns(self):
        from tests.functional.user_add import user_add
        user_add("John", "Doe")
        user_add("John", "Doe")

        time.sleep(3)

        auth = Auth()
        auth.connect()

        max_tries = 20
        while max_tries > 0:
            recipient1 = auth.find_recipient('*****@*****.**')
            recipient2 = auth.find_recipient('*****@*****.**')

            if not recipient1 or not recipient2:
                time.sleep(1)
                max_tries -= 1
            else:
                break

        imap = IMAP()
        imap.connect()

        folders = imap.lm('user/[email protected]')
        self.assertEqual(len(folders), 1, "No INBOX found for first John")

        folders = imap.lm('user/[email protected]')
        self.assertEqual(len(folders), 1, "No INBOX found for second John")
Exemplo n.º 4
0
    def connect(self, uri):
        """
            Dummy connect function that checks if the server that we want to
            connect to is actually the server we are connected to.

            Uses pykolab.imap.IMAP.connect() in the background.
        """
        port = None

        result = urlparse(uri)

        if hasattr(result, 'hostname'):
            scheme = result.scheme
            hostname = result.hostname
            port = result.port
        else:
            scheme = uri.split(':')[0]
            (hostname, port) = uri.split('/')[2].split(':')

        if not port:
            if scheme == 'imap':
                port = 143
            else:
                port = 993

        if hostname == self.server:
            return

        imap = IMAP()
        imap.connect(uri=uri)

        if not self.SEP == self.separator:
            self.separator = self.SEP
Exemplo n.º 5
0
def execute(*args, **kw):
    """
        Delete a message from a mail folder
    """

    try:
        folder = conf.cli_args.pop(0)

        try:
            uid = conf.cli_args.pop(0)
        except:
            log.error(_("Specify a UID"))
            sys.exit(1)
    except:
        log.error(_("Specify a folder"))
        sys.exit(1)

    imap = IMAP()
    imap.connect()

    _folder = imap.lm(folder)

    if _folder == None or _folder == []:
        log.error(_("No such folder"))
        sys.exit(1)

    imap.set_acl(folder, 'cyrus-admin', 'lrswt')

    imap.select(folder)

    imap.store(uid, '+FLAGS', '\\Deleted')
Exemplo n.º 6
0
    def test_001_inbox_created(self):
        time.sleep(2)
        imap = IMAP()
        imap.connect()

        folders = imap.lm('user/%(local)s@%(domain)s' % (self.user))
        self.assertEqual(len(folders), 1)
Exemplo n.º 7
0
    def connect(self, uri):
        """
            Dummy connect function that checks if the server that we want to
            connect to is actually the server we are connected to.

            Uses pykolab.imap.IMAP.connect() in the background.
        """
        port = None

        result = urlparse(uri)

        if hasattr(result, 'hostname'):
            scheme = result.scheme
            hostname = result.hostname
            port = result.port
        else:
            scheme = uri.split(':')[0]
            (hostname, port) = uri.split('/')[2].split(':')

        if not port:
            if scheme == 'imap':
                port = 143
            else:
                port = 993

        if hostname == self.server:
            return

        imap = IMAP()
        imap.connect(uri=uri)

        if not self.SEP == self.separator:
            self.separator = self.SEP
Exemplo n.º 8
0
    def test_001_inbox_created(self):
        time.sleep(2)
        imap = IMAP()
        imap.connect()

        folders = imap.lm('user/%(local)s@%(domain)s' % (self.user))
        self.assertEqual(len(folders), 1)
Exemplo n.º 9
0
def execute(*args, **kw):
    """
        List mailboxes
    """

    searches = []

    # See if conf.cli_args components make sense.
    for arg in conf.cli_args:
        if arg == '*':
            searches.append(arg)
        if arg.startswith('user'):
            searches.append(arg)
        if arg.startswith('shared'):
            searches.append(arg)
        if arg.startswith('DELETED'):
            searches.append(arg)
        if arg.startswith('news'):
            searches.append(arg)

    if len(searches) == 0:
        searches = [ '' ]

    imap = IMAP()
    imap.connect()

    folders = []

    for search in searches:
        log.debug(_("Appending folder search for %r") % (search), level=8)
        folders.extend(imap.lm(search))

    for folder in folders:
        print folder
Exemplo n.º 10
0
    def test_001_inbox_created(self):
        imap = IMAP()
        imap.connect()

        folders = imap.lm('user/%(local)s@%(domain)s' % (self.john))
        self.assertEqual(len(folders), 1)
        
        folders = imap.lm('user/%(local)s@%(domain)s' % (self.jane))
        self.assertEqual(len(folders), 1)
Exemplo n.º 11
0
def execute(*args, **kw):
    """
        Synchronize or display changes
    """

    imap = IMAP()

    if not conf.connect_server == None:
        imap.connect(server=conf.connect_server)
    else:
        imap.connect()

    auth = Auth()
    auth.connect()

    domains = auth.list_domains()

    folders = imap.lm()

    imap_domains_not_domains = []

    for folder in folders:
        if len(folder.split('@')) > 1 and not folder.startswith('DELETED'):
            _folder_domain = folder.split('@')[-1]
            if not _folder_domain in list(set(domains.keys() + domains.values())):
                imap_domains_not_domains.append(folder.split('@')[-1])

    imap_domains_not_domains = list(set(imap_domains_not_domains))

    log.debug(_("Domains in IMAP not in LDAP: %r") % (imap_domains_not_domains), level=8)

    if len(imap_domains_not_domains) > 0:
        for domain in imap_domains_not_domains:
            folders = []

            folders.extend(imap.lm('shared/%%@%s' % (domain)))
            folders.extend(imap.lm('user/%%@%s' % (domain)))

            for folder in folders:
                if conf.delete:
                    if conf.dry_run:
                        if not folder.split('/')[0] == 'shared':
                            log.warning(_("No recipients for '%s' (would have deleted the mailbox if not for --dry-run)!") % ('/'.join(folder.split('/')[1:])))
                        else:
                            continue
                    else:
                        if not '/'.join(folder.split('/')[0]) == 'shared':
                            log.info(_("Deleting mailbox '%s' because it has no recipients") % (folder))
                            try:
                                imap.dm(folder)
                            except Exception, errmsg:
                                log.error(_("An error occurred removing mailbox %r: %r") % (folder, errmsg))
                        else:
                            log.info(_("Not automatically deleting shared folder '%s'") % (folder))
                else:
                    log.warning(_("No recipients for '%s' (use --delete to delete)!") % ('/'.join(folder.split('/')[1:])))
Exemplo n.º 12
0
def _synchronize(*args, **kw):
    log.info(
        _("Worker process %s handling %s") %
        (multiprocessing.current_process().name, kw['dn']))

    entry = utils.normalize(kw)

    if not entry.has_key('mail'):
        return

    if not 'kolabinetorgperson' in entry['objectclass']:
        return

    imap = IMAP()
    imap.connect()

    if not imap.user_mailbox_exists(entry['mail']):
        if entry.has_key('mailhost'):
            server = entry['mailhost']
        else:
            server = None

        imap.user_mailbox_create(entry['mail'], server=server)

    imap.disconnect()
Exemplo n.º 13
0
    def test_004_user_additional_folders_created(self):
        time.sleep(2)
        imap = IMAP()
        imap.connect()

        ac_folders = conf.get_raw('kolab', 'autocreate_folders')
        exec("ac_folders = %s" % (ac_folders))

        folders = imap.lm('user/%(local)s/*@%(domain)s' % (self.user))

        self.assertEqual(len(folders), len(ac_folders.keys()))
Exemplo n.º 14
0
    def test_004_user_additional_folders_created(self):
        time.sleep(2)
        imap = IMAP()
        imap.connect()

        ac_folders = conf.get_raw('kolab', 'autocreate_folders')
        exec("ac_folders = %s" % (ac_folders))

        folders = imap.lm('user/%(local)s/*@%(domain)s' % (self.user))

        self.assertEqual(len(folders), len(ac_folders.keys()))
Exemplo n.º 15
0
    def test_002_autocreate_folders_created(self):
        time.sleep(2)
        imap = IMAP()
        imap.connect()

        exec("ac_folders = %s" % (conf.get_raw(conf.get('kolab', 'primary_domain'), 'autocreate_folders')))

        folders = imap.lm('user/%(local)s/*@%(domain)s' % (self.user))

        print folders
        print ac_folders.keys()

        self.assertEqual(len(folders), len(ac_folders.keys()))
Exemplo n.º 16
0
    def check_message_received(self, subject, from_addr=None, mailbox=None):
        if mailbox is None:
            mailbox = self.john['mailbox']

        imap = IMAP()
        imap.connect()

        mailbox = imap.folder_quote(mailbox)
        imap.set_acl(mailbox, "cyrus-admin", "lrs")
        imap.imap.m.select(mailbox)

        found = None
        retries = 15

        while not found and retries > 0:
            retries -= 1

            typ, data = imap.imap.m.search(None, '(UNDELETED HEADER FROM "%s")' % (from_addr) if from_addr else 'UNDELETED')
            for num in data[0].split():
                typ, msg = imap.imap.m.fetch(num, '(RFC822)')
                message = message_from_string(msg[0][1])
                if message['Subject'] == subject:
                    found = message
                    break

            time.sleep(1)

        imap.disconnect()

        return found
Exemplo n.º 17
0
    def test_002_autocreate_folders_created(self):
        time.sleep(2)
        imap = IMAP()
        imap.connect()

        exec("ac_folders = %s" % (conf.get_raw(
            conf.get('kolab', 'primary_domain'), 'autocreate_folders')))

        folders = imap.lm('user/%(local)s/*@%(domain)s' % (self.user))

        print folders
        print ac_folders.keys()

        self.assertEqual(len(folders), len(ac_folders.keys()))
Exemplo n.º 18
0
def execute(*args, **kw):
    """
        Undelete mailbox
    """

    target_folder = None

    undelete_folder = conf.cli_args.pop(0)
    if len(conf.cli_args) > 0:
        target_folder = conf.cli_args.pop(0)

    imap = IMAP()
    imap.connect()
    imap.undelete_mailfolder(undelete_folder, target_folder)
Exemplo n.º 19
0
def execute(*args, **kw):
    """
        List mailboxes
    """

    try:
        aci_subject = conf.cli_args.pop(0)
    except:
        aci_subject = None

    imap = IMAP()
    imap.connect()

    folders = imap.lm()

    for folder in folders:
        acls = imap.list_acls(folder)

        if not aci_subject == None:
            if aci_subject in acls.keys():
                log.debug(_("Deleting ACL %s for subject %s on folder %s") %
                          (acls[aci_subject], aci_subject, folder),
                          level=8)

                imap.set_acl(folder, aci_subject, '')
    def check_resource_calendar_event(self, mailbox, uid=None):
        imap = IMAP()
        imap.connect()

        imap.set_acl(mailbox, "cyrus-admin", "lrs")
        imap.imap.m.select(imap.folder_quote(mailbox))

        found = None
        retries = 10

        while not found and retries > 0:
            retries -= 1

            typ, data = imap.imap.m.search(None, '(UNDELETED HEADER SUBJECT "%s")' % (uid) if uid else '(UNDELETED HEADER X-Kolab-Type "application/x-vnd.kolab.event")')
            for num in data[0].split():
                typ, data = imap.imap.m.fetch(num, '(RFC822)')
                event_message = message_from_string(data[0][1])

                # return matching UID or first event found
                if uid and event_message['subject'] != uid:
                    continue

                found = event_from_message(event_message)
                if found:
                    break

            time.sleep(1)

        imap.disconnect()

        return found
Exemplo n.º 21
0
    def test_001_user_rename(self):
        """
            Rename user "Doe, John" to "Sixpack, Joe" and verify the recipient
            policy is applied, and the IMAP INBOX folder for the user is
            renamed.
        """
        auth = Auth()
        auth.connect()
        recipient = auth.find_recipient('*****@*****.**')
        user_info = wap_client.user_info(recipient)

        if not user_info.has_key('mailhost'):
            from tests.functional.synchronize import synchronize_once
            synchronize_once()

        imap = IMAP()
        imap.connect()
        folders = imap.lm('user/[email protected]')
        self.assertEqual(len(folders), 1)

        auth = Auth()
        auth.connect()
        recipient = auth.find_recipient("%(local)s@%(domain)s" % (self.user))

        user_info = wap_client.user_info(recipient)
        user_info['sn'] = 'Sixpack'
        user_info['givenname'] = 'Joe'
        user_info['uid'] = 'sixpack'
        user_edit = wap_client.user_edit(recipient, user_info)

        time.sleep(2)

        print imap.lm()

        user_info = wap_client.user_info('uid=sixpack,ou=People,dc=example,dc=org')
        if not user_info['mail'] == '*****@*****.**':
            from tests.functional.synchronize import synchronize_once
            synchronize_once()
            user_info = wap_client.user_info('uid=sixpack,ou=People,dc=example,dc=org')

        self.assertEqual(user_info['mail'], '*****@*****.**')

        print imap.lm()

        folders = imap.lm('user/[email protected]')
        self.assertEqual(len(folders), 0, "INBOX for john.doe still exists")

        folders = imap.lm('user/[email protected]')
        self.assertEqual(len(folders), 1, "INBOX for joe.sixpack does not exist")
    def purge_mailbox(self, mailbox):
        imap = IMAP()
        imap.connect()
        imap.set_acl(mailbox, "cyrus-admin", "lrwcdest")
        imap.imap.m.select(imap.folder_quote(mailbox))

        typ, data = imap.imap.m.search(None, 'ALL')
        for num in data[0].split():
            imap.imap.m.store(num, '+FLAGS', '\\Deleted')

        imap.imap.m.expunge()
        imap.disconnect()
Exemplo n.º 23
0
    def __init__(self, *args, **kw):
        # load pykolab conf
        conf = pykolab.getConf()
        if not hasattr(conf, 'defaults'):
            conf.finalize_conf(fatal=False)

        self.imap = IMAP()
Exemplo n.º 24
0
def execute(*args, **kw):
    """
        Transfer mailbox
    """

    if len(conf.cli_args) > 1:
        mailfolder = conf.cli_args.pop(0)
        target_server = conf.cli_args.pop(0)

    if len(conf.cli_args) > 0:
        target_partition = conf.cli_args.pop(0)

    imap = IMAP()
    imap.connect()

    mbox_parts = imap.parse_mailfolder(mailfolder)

    if mbox_parts['domain'] == None:
        domain = conf.get('kolab', 'primary_domain')
        user_identifier = mbox_parts['path_parts'][1]
    else:
        domain = mbox_parts['domain']
        user_identifier = "%s@%s" % (mbox_parts['path_parts'][1], mbox_parts['domain'])

    auth = Auth(domain=domain)
    auth.connect()

    user = auth.find_recipient(user_identifier)

    source_server = imap.user_mailbox_server(mailfolder)
    imap.connect(server=source_server)
    imap.imap.xfer(mailfolder, target_server)

    if not user == None and not len(user) < 1:
        auth.set_entry_attributes(domain, user, {'mailhost': target_server})
Exemplo n.º 25
0
def execute(*args, **kw):
    """
        List mailboxes
    """

    try:
        aci_subject = conf.cli_args.pop(0)
    except:
        aci_subject = None

    imap = IMAP()
    imap.connect()

    folders = imap.lm()

    for folder in folders:
        acls = imap.list_acls(folder)

        if not aci_subject == None:
            if aci_subject in acls.keys():
                log.debug(_("Deleting ACL %s for subject %s on folder %s") % (
                        acls[aci_subject],
                        aci_subject,
                        folder
                    ), level=8)

                imap.set_acl(folder, aci_subject, '')

        #else:
            #for _aci_subject in acls.keys():
                # connect to auth(!)
                # find recipient result_attr=aci_subject
                # if no entry, expire acl
Exemplo n.º 26
0
def execute(*args, **kw):
    """
        List deleted mailboxes
    """
    imap = IMAP()
    imap.connect()

    auth = Auth()
    auth.connect()

    domains = auth.list_domains()

    folders = []
    for domain in list(set(domains.keys())):
        folders.extend(imap.lm("DELETED/*@%s" % (domain)))

    folders.extend(imap.lm("DELETED/*"))

    print "Deleted folders:"

    for folder in folders:
        utf8_folder = imap_utf7.decode(folder).encode('utf-8')
        mbox_parts = imap.parse_mailfolder(utf8_folder)
        ts = datetime.datetime.fromtimestamp(int(mbox_parts['hex_timestamp'], 16))

        if not conf.raw:
            print "%s (Deleted at %s)" % (utf8_folder, ts)
        else:
            print "%s (Deleted at %s)" % (folder, ts)
Exemplo n.º 27
0
    def test_002_send_forwarded_email(self):
        import smtplib
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders

        smtp = smtplib.SMTP('localhost', 10026)
        subject = "%s" % (time.time())
        body = "This is a test message"
        msg = MIMEMultipart()
        msg['From'] = '"Doe, Jane" <*****@*****.**>'
        msg['To'] = '"Doe, John" <*****@*****.**>'
        msg['Subject'] = subject
        msg['Date'] = formatdate(localtime=True)
        msg.attach(MIMEText(body))

        send_to = '*****@*****.**'
        send_from = '*****@*****.**'

        smtp.sendmail(send_from, send_to, msg.as_string())

        imap = IMAP()
        imap.connect()
        imap.set_acl("user/[email protected]", "cyrus-admin", "lrs")
        imap.imap.m.select("user/[email protected]")

        found = False
        max_tries = 20

        while not found and max_tries > 0:
            max_tries -= 1

            typ, data = imap.imap.m.search(None, 'ALL')
            for num in data[0].split():
                typ, msg = imap.imap.m.fetch(num, '(RFC822)')
                _msg = message_from_string(msg[0][1])
                if _msg['Subject'] == subject:
                    found = True

            time.sleep(1)

        if not found:
            raise Exception
Exemplo n.º 28
0
class IMAPDataHandler(object):
    """
        Collector handler to provide metadata from IMAP
    """

    def __init__(self, *args, **kw):
        # load pykolab conf
        conf = pykolab.getConf()
        if not hasattr(conf, 'defaults'):
            conf.finalize_conf(fatal=False)

        self.imap = IMAP()

    def register(self, callback):
        interests = {
                'GETMETADATA': {
                        'callback': self.get_imap_folder_metadata
                    },
                'GETACL': {
                        'callback': self.get_imap_folder_acl
                    }
            }

        callback(interests)

    def get_imap_folder_metadata(self, notification):
        notification = json.loads(notification)
        log.debug("GETMETADATA for %r" % (notification), level=9)

        # split the uri parameter into useful parts
        uri = parse_imap_uri(notification['uri'])
        folder_path = imap_folder_path(uri)

        # get metadata using pykolab's imap module
        metadata = {}
        try:
            self.imap.connect()
            metadata = self.imap.get_metadata(folder_path)[folder_path]
            self.imap.disconnect()
        except Exception, e:
            log.warning("Failed to get metadata for %r: %r", folder_path, e)

        notification['metadata'] = metadata

        return json.dumps(notification)
Exemplo n.º 29
0
    def test_003_folders_metadata_set(self):
        imap = IMAP()
        imap.connect()

        exec("ac_folders = %s" % (conf.get_raw(
            conf.get('kolab', 'primary_domain'), 'autocreate_folders')))

        folders = []
        folders.extend(imap.lm('user/%(local)s@%(domain)s' % (self.user)))
        folders.extend(imap.lm('user/%(local)s/*@%(domain)s' % (self.user)))

        for folder in folders:
            metadata = imap.get_metadata(folder)

            folder_name = '/'.join(folder.split('/')[2:]).split('@')[0]
            if folder_name in ac_folders:
                if 'annotations' in ac_folders[folder_name]:
                    for _annotation in ac_folders[folder_name]['annotations']:
                        if _annotation.startswith('/private/'):
                            continue

                        _annotation_value = ac_folders[folder_name][
                            'annotations'][_annotation]
                        self.assertTrue(
                            _annotation in metadata[metadata.keys().pop()])
                        self.assertEqual(
                            _annotation_value,
                            metadata[metadata.keys().pop()][_annotation])
Exemplo n.º 30
0
def execute(*args, **kw):
    """
        Delete mailbox
    """

    if len(conf.cli_args) < 1:
        print >> sys.stderr, _("No mailbox specified")
        sys.exit(1)

    imap = IMAP()

    imap.connect()

    delete_folders = []
    while len(conf.cli_args) > 0:
        folder = conf.cli_args.pop(0)
        folders = imap.list_folders(folder)

        if len(folders) < 1:
            print >> sys.stderr, _("No such folder(s): %s") % (folder)

        delete_folders.extend(folders)

    if len(delete_folders) == 0:
        print >> sys.stderr, _("No folders to delete.")
        sys.exit(1)

    for delete_folder in delete_folders:
        try:
            imap.delete_mailfolder(delete_folder)
        except Exception, errmsg:
            log.error(_("Could not delete mailbox '%s'") % (delete_folder))
    def purge_mailbox(self, mailbox):
        imap = IMAP()
        imap.connect()
        imap.set_acl(mailbox, "cyrus-admin", "lrwcdest")
        imap.imap.m.select(imap.folder_quote(mailbox))

        typ, data = imap.imap.m.search(None, 'ALL')
        for num in data[0].split():
            imap.imap.m.store(num, '+FLAGS', '\\Deleted')

        imap.imap.m.expunge()
        imap.disconnect()
Exemplo n.º 32
0
def execute(*args, **kw):
    """
        List mailboxes
    """

    imap = IMAP()

    if not conf.connect_server == None:
        imap.connect(server=conf.connect_server)
    else:
        imap.connect()

    print imap.get_metadata("")
Exemplo n.º 33
0
def execute(*args, **kw):
    """
        List deleted mailboxes
    """
    imap = IMAP()
    imap.connect()

    auth = Auth()
    auth.connect()

    domains = auth.list_domains()

    folders = []
    for domain in domains.keys():
        print "%s: %d" % (domain,len(imap.lm("user/%%@%s" % (domain))))

    null_realm = len(imap.lm("user/%%"))

    if null_realm > 0:
        print "null: %d" % (null_realm)
    def setup_class(self, *args, **kw):
        funcs.purge_resources()
        self.room1 = funcs.resource_add("confroom", "Room 101")
        self.room2 = funcs.resource_add("confroom", "Conference Room B-222")
        self.rooms = funcs.resource_add("collection", "Rooms", [self.room1['dn'], self.room2['dn']])

        time.sleep(1)
        synchronize_once()

        module_resources.imap = IMAP()
        module_resources.imap.connect()
Exemplo n.º 35
0
    def __init__(self, *args, **kw):
        if kw.has_key('domain') and not kw['domain'] == None:
            self.domain = kw['domain']
        else:
            self.domain = conf.get('kolab', 'primary_domain')

        # Placeholder primary_domain => [secondary_domains]. Should be updated
        # on auth backend _connect().
        self.domains = None

        self.imap = IMAP()
        self.domain_rootdns = {}
Exemplo n.º 36
0
    def update_calendar_event(self, uid, start=None, summary=None, sequence=0, user=None):
        if user is None:
            user = self.john

        event = self.check_user_calendar_event(user['kolabcalendarfolder'], uid)
        if event:
            if start is not None:
                event.set_start(start)
            if summary is not None:
                event.set_summary(summary)
            if sequence is not None:
                event.set_sequence(sequence)

            imap = IMAP()
            imap.connect()

            mailbox = imap.folder_quote(user['kolabcalendarfolder'])
            imap.set_acl(mailbox, "cyrus-admin", "lrswipkxtecda")
            imap.imap.m.select(mailbox)

            return imap.imap.m.append(
                mailbox,
                None,
                None,
                event.to_message().as_string()
            )

        return False
Exemplo n.º 37
0
    def test_001_two_johns(self):
        from tests.functional.user_add import user_add
        user_add("John", "Doe")
        user_add("John", "Doe")

        time.sleep(3)

        auth = Auth()
        auth.connect()

        max_tries = 20
        while max_tries > 0:
            recipient1 = auth.find_recipient('*****@*****.**')
            recipient2 = auth.find_recipient('*****@*****.**')

            if not recipient1 or not recipient2:
                time.sleep(1)
                max_tries -= 1
            else:
                break

        imap = IMAP()
        imap.connect()

        folders = imap.lm('user/[email protected]')
        self.assertEqual(len(folders), 1, "No INBOX found for first John")

        folders = imap.lm('user/[email protected]')
        self.assertEqual(len(folders), 1, "No INBOX found for second John")
Exemplo n.º 38
0
def execute(*args, **kw):
    """
        List deleted mailboxes
    """

    try:
        domain = conf.cli_args.pop(0)
    except:
        domain = utils.ask_question(_("Domain"))

    imap = IMAP()
    imap.connect()

    auth = Auth()
    auth.connect()

    domains = auth.list_domains()

    folders = []
    for primary,secondaries in domains:
        if not domain == primary and not domain in secondaries:
            continue

        folders.extend(imap.lm("user/%%@%s" % (primary)))
        for secondary in secondaries:
            folders.extend(imap.lm("user/%%@%s" % (secondary)))

    print "Deleted folders:"

    for folder in folders:
        if not conf.raw:
            print imap_utf7.decode(folder)
        else:
            print folder
Exemplo n.º 39
0
    def create_task_assignment(self, due=None, summary="test", sequence=0, user=None, attendees=None):
        if due is None:
            due = datetime.datetime.now(pytz.timezone("Europe/Berlin")) + datetime.timedelta(days=2)
        if user is None:
            user = self.john
        if attendees is None:
            attendees = [self.jane]

        todo = pykolab.xml.Todo()
        todo.set_due(due)
        todo.set_organizer(user['mail'], user['displayname'])

        for attendee in attendees:
            todo.add_attendee(attendee['mail'], attendee['displayname'], role="REQ-PARTICIPANT", participant_status="NEEDS-ACTION", rsvp=True)

        todo.set_summary(summary)
        todo.set_sequence(sequence)

        imap = IMAP()
        imap.connect()

        mailbox = imap.folder_quote(user['kolabtasksfolder'])
        imap.set_acl(mailbox, "cyrus-admin", "lrswipkxtecda")
        imap.imap.m.select(mailbox)

        result = imap.imap.m.append(
            mailbox,
            None,
            None,
            todo.to_message().as_string()
        )

        return todo.get_uid()
Exemplo n.º 40
0
def execute(*args, **kw):
    """
        List deleted mailboxes
    """
    imap = IMAP()
    imap.connect()

    auth = Auth()
    auth.connect()

    domains = auth.list_domains()

    folders = []
    for domain in list(set(domains.keys())):
        folders.extend(imap.lm("DELETED/*@%s" % (domain)))

    folders.extend(imap.lm("DELETED/*"))

    print "Deleted folders:"

    for folder in folders:
        mbox_parts = imap.parse_mailfolder(folder)

        if not conf.raw:
            print "%s (Deleted at %s)" % (imap_utf7.decode(folder).encode('utf-8'), datetime.datetime.fromtimestamp(int(mbox_parts['hex_timestamp'], 16)))
        else:
            print "%s (Deleted at %s)" % (folder, datetime.datetime.fromtimestamp(int(mbox_parts['hex_timestamp'], 16)))
Exemplo n.º 41
0
    def check_user_imap_object(self, mailbox, uid=None, type='event'):
        imap = IMAP()
        imap.connect()

        mailbox = imap.folder_quote(mailbox)
        imap.set_acl(mailbox, "cyrus-admin", "lrs")
        imap.imap.m.select(mailbox)

        found = None
        retries = 15

        while not found and retries > 0:
            retries -= 1

            typ, data = imap.imap.m.search(None, '(UNDELETED HEADER SUBJECT "%s")' % (uid) if uid else '(UNDELETED HEADER X-Kolab-Type "application/x-vnd.kolab.' + type + '")')
            for num in data[0].split():
                typ, data = imap.imap.m.fetch(num, '(RFC822)')
                object_message = message_from_string(data[0][1])

                # return matching UID or first event found
                if uid and object_message['subject'] != uid:
                    continue

                if type == 'task':
                    found = todo_from_message(object_message)
                else:
                    found = event_from_message(object_message)

                if found:
                    break

            time.sleep(1)

        return found
Exemplo n.º 42
0
    def test_005_user_folders_metadata_set(self):
        imap = IMAP()
        imap.connect()

        ac_folders = conf.get_raw('kolab', 'autocreate_folders')
        exec("ac_folders = %s" % (ac_folders))

        folders = []
        folders.extend(imap.lm('user/%(local)s@%(domain)s' % (self.user)))
        folders.extend(imap.lm('user/%(local)s/*@%(domain)s' % (self.user)))

        for folder in folders:
            metadata = imap.get_metadata(folder)
            print metadata

            folder_name = '/'.join(folder.split('/')[2:]).split('@')[0]
            if ac_folders.has_key(folder_name):
                if ac_folders[folder_name].has_key('annotations'):
                    for _annotation in ac_folders[folder_name]['annotations'].keys():
                        if _annotation.startswith('/private'):
                            continue

                        _annotation_value = ac_folders[folder_name]['annotations'][_annotation]
                        self.assertTrue(metadata[metadata.keys().pop()].has_key(_annotation))
                        self.assertEqual(_annotation_value, metadata[metadata.keys().pop()][_annotation])
Exemplo n.º 43
0
    def check_message_delivered(self, subject):
        imap = IMAP()
        imap.connect()
        imap.set_acl("user/[email protected]", "cyrus-admin", "lrs")
        imap.imap.m.select("user/[email protected]")

        found = False
        max_tries = 20

        while not found and max_tries > 0:
            max_tries -= 1

            typ, data = imap.imap.m.search(None, 'ALL')
            for num in data[0].split():
                typ, msg = imap.imap.m.fetch(num, '(RFC822)')
                _msg = message_from_string(msg[0][1])
                if _msg['Subject'] == subject:
                    found = True

            time.sleep(1)

        return found
Exemplo n.º 44
0
def purge_imap():
    time.sleep(2)

    imap = IMAP()
    imap.connect()

    for folder in imap.lm():
        try:
            imap.dm(folder)
        except:
            pass
Exemplo n.º 45
0
    def test_006_user_subscriptions(self):
        imap = IMAP()
        imap.connect(login=False)
        login = conf.get('cyrus-imap', 'admin_login')
        password = conf.get('cyrus-imap', 'admin_password')
        imap.login_plain(login, password, '*****@*****.**')

        folders = imap.lm()
        self.assertTrue("INBOX" in folders)

        folders = imap.imap.lsub()
        self.assertTrue("Calendar" in folders)
Exemplo n.º 46
0
    def test_001_inbox_created(self):
        imap = IMAP()
        imap.connect()

        folders = imap.lm('user/%(local)s@%(domain)s' % (self.john))
        self.assertEqual(len(folders), 1)

        folders = imap.lm('user/%(local)s@%(domain)s' % (self.jane))
        self.assertEqual(len(folders), 1)
Exemplo n.º 47
0
def execute(*args, **kw):
    """
        List mailboxes
    """

    imap = IMAP()

    if not conf.connect_server == None:
        imap.connect(server=conf.connect_server)
    else:
        imap.connect()

    print imap.get_metadata("")
Exemplo n.º 48
0
def execute(*args, **kw):
    """
        Undelete mailbox
    """

    target_folder = None

    undelete_folder = conf.cli_args.pop(0)
    if len(conf.cli_args) > 0:
        target_folder = conf.cli_args.pop(0)

    imap = IMAP()
    imap.connect()
    imap.undelete_mailfolder(undelete_folder, target_folder)
Exemplo n.º 49
0
def execute(*args, **kw):
    """
        Transfer mailbox
    """

    if len(conf.cli_args) > 1:
        mailfolder = conf.cli_args.pop(0)
        target_server = conf.cli_args.pop(0)

    if len(conf.cli_args) > 0:
        target_partition = conf.cli_args.pop(0)

    imap = IMAP()
    imap.connect()

    mbox_parts = imap.parse_mailfolder(mailfolder)

    if mbox_parts['domain'] == None:
        domain = conf.get('kolab', 'primary_domain')
        user_identifier = mbox_parts['path_parts'][1]
    else:
        domain = mbox_parts['domain']
        user_identifier = "%s@%s" % (mbox_parts['path_parts'][1],
                                     mbox_parts['domain'])

    auth = Auth(domain=domain)
    auth.connect()

    user = auth.find_recipient(user_identifier)

    source_server = imap.user_mailbox_server(mailfolder)
    imap.connect(server=source_server)
    imap.imap.xfer(mailfolder, target_server)

    if not user == None and not len(user) < 1:
        auth.set_entry_attributes(domain, user, {'mailhost': target_server})
Exemplo n.º 50
0
def execute(*args, **kw):
    """
        List mailboxes
    """

    searches = []

    # See if conf.cli_args components make sense.
    for arg in conf.cli_args:
        if arg == '*':
            searches.append(arg)
        if arg.startswith('user'):
            searches.append(arg)
        if arg.startswith('shared'):
            searches.append(arg)
        if arg.startswith('DELETED'):
            searches.append(arg)
        if arg.startswith('news'):
            searches.append(arg)

    if len(searches) == 0:
        searches = [ '' ]

    imap = IMAP()

    if not conf.connect_server == None:
        imap.connect(server=conf.connect_server)
    else:
        imap.connect()

    folders = []

    for search in searches:
        log.debug(_("Appending folder search for %r") % (search), level=8)
        folders.extend(imap.lm(imap_utf7.encode(search)))

    for folder in folders:
        if not conf.raw:
            print imap_utf7.decode(folder)
        else:
            print folder
Exemplo n.º 51
0
    def test_002_send_forwarded_email(self):
        import smtplib
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders

        smtp = smtplib.SMTP('localhost', 10026)
        subject = "%s" % (time.time())
        body = "This is a test message"
        msg = MIMEMultipart()
        msg['From'] = '"Doe, Jane" <*****@*****.**>'
        msg['To'] = '"Doe, John" <*****@*****.**>'
        msg['Subject'] = subject
        msg['Date'] = formatdate(localtime=True)
        msg.attach(MIMEText(body))

        send_to = '*****@*****.**'
        send_from = '*****@*****.**'

        smtp.sendmail(send_from, send_to, msg.as_string())

        imap = IMAP()
        imap.connect()
        imap.set_acl("user/[email protected]", "cyrus-admin", "lrs")
        imap.imap.m.select("user/[email protected]")

        found = False
        max_tries = 20

        while not found and max_tries > 0:
            max_tries -= 1

            typ, data = imap.imap.m.search(None, 'ALL')
            for num in data[0].split():
                typ, msg = imap.imap.m.fetch(num, '(RFC822)')
                _msg = message_from_string(msg[0][1])
                if _msg['Subject'] == subject:
                    found = True

            time.sleep(1)

        if not found:
            raise Exception
Exemplo n.º 52
0
def execute(*args, **kw):
    """
        List deleted mailboxes
    """
    imap = IMAP()
    imap.connect()

    auth = Auth()
    auth.connect()

    domains = auth.list_domains()

    folders = []
    for domain in domains.keys():
        print "%s: %d" % (domain, len(imap.lm("user/%%@%s" % (domain))))

    null_realm = len(imap.lm("user/%%"))

    if null_realm > 0:
        print "null: %d" % (null_realm)
Exemplo n.º 53
0
    def check_message_delivered(self, subject):
        imap = IMAP()
        imap.connect()
        imap.set_acl("user/[email protected]", "cyrus-admin", "lrs")
        imap.imap.m.select("user/[email protected]")

        found = False
        max_tries = 20

        while not found and max_tries > 0:
            max_tries -= 1

            typ, data = imap.imap.m.search(None, 'ALL')
            for num in data[0].split():
                typ, msg = imap.imap.m.fetch(num, '(RFC822)')
                _msg = message_from_string(msg[0][1])
                if _msg['Subject'] == subject:
                    found = True

            time.sleep(1)

        return found
Exemplo n.º 54
0
                                help    = _("List mailboxes on server SERVER only."))

def description():
    return """List quota for a folder."""

def execute(*args, **kw):
    """
        List quota for a mailbox
    """

    try:
        quota_folder = conf.cli_args.pop(0)
    except IndexError, e:
        quota_folder = '*'

    imap = IMAP()

    if not conf.connect_server == None:
        imap.connect(server=conf.connect_server)
    else:
        imap.connect()

    folders = []

    quota_folders = imap.list_folders(quota_folder)
    for quota_folder in quota_folders:
        try:
            (used, quota) = imap.get_quota(quota_folder)
            print "Folder: %s" % (quota_folder)
            if not used == None and not quota == None:
                if quota == 0:
Exemplo n.º 55
0
def execute(*args, **kw):
    """
        List mailboxes
    """

    auth = Auth()
    domains = auth.list_domains()

    imap = IMAP()
    imap.connect()

    domain_folders = {}

    subjects = []
    # Placeholder for subjects that would have already been deleted
    subjects_deleted = []

    for domain in domains.keys():
        domain_folders[domain] = imap.lm("user/%%@%s" % (domain))

    for domain in domain_folders.keys():
        auth = Auth(domain=domain)
        auth.connect(domain)

        for folder in domain_folders[domain]:
            user = folder.replace('user/', '')

            try:
                recipient = auth.find_recipient(user)
            except ldap.NO_SUCH_OBJECT, errmsg:
                if not user in subjects_deleted and conf.dryrun:
                    subjects_deleted.append(user)

                if conf.dryrun:
                    log.info(
                        _("Would have deleted folder 'user/%s' (dryrun)") %
                        (user))
                else:
                    log.info(_("Deleting folder 'user/%s'") % (user))
                continue

            if len(recipient) == 0 or recipient == []:
                if not user in subjects_deleted and conf.dryrun:
                    subjects_deleted.append(user)

                if conf.dryrun:
                    log.info(
                        _("Would have deleted folder 'user/%s' (dryrun)") %
                        (user))
                else:
                    log.info(_("Deleting folder 'user/%s'") % (user))
                    try:
                        imap.dm(folder)
                    except:
                        log.error(
                            _("Error deleting folder 'user/%s'") % (user))
            else:
                log.debug(_("Valid recipient found for 'user/%s'") % (user),
                          level=6)

                if not user in subjects:
                    subjects.append(user)
Exemplo n.º 56
0
    return imap_utf7.encode(
        "user/{username}/[email protected]".format(username=user))


def appendEvent(user, event):
    """event must be a ical object (python icalendar Event)"""
    e = event_from_ical(event)  # construct a kolab object
    folder = calendar(user)
    imap.append(folder, None, None, e.to_message().as_string())


if __name__ == '__main__':
    conf = pykolab.getConf()
    conf.finalize_conf()

    imap = IMAP()
    imap.connect()

    user = "******"

    start = datetime(2015,
                     1,
                     1,
                     0,
                     0,
                     0,
                     tzinfo=pytz.timezone("Europe/Berlin"))
    end = datetime(2015, 1, 1, 10, 0, 0, tzinfo=pytz.timezone("Europe/Berlin"))
    event = ical.createEvent(start, end)

    # Admin normally has no right to do anything with the mailbox
Exemplo n.º 57
0
            try:
                partition = conf.cli_args.pop(0)
            except IndexError, errmsg:
                partition = None
        except IndexError, errmsg:
            print >> sys.stderr, _("No target mailbox name specified")
    except IndexError, errmsg:
        print >> sys.stderr, _("No source mailbox name specified")
        sys.exit(1)

    if len(source_folder.split('@')) > 1:
        domain = source_folder.split('@')[1]
    else:
        domain = conf.get('kolab', 'primary_domain')

    imap = IMAP()
    imap.connect(domain=domain)

    if not imap.has_folder(source_folder):
        print >> sys.stderr, _("Source folder %r does not exist") % (
            source_folder)
        sys.exit(1)

    if imap.has_folder(target_folder) and partition == None:
        print >> sys.stderr, _("Target folder %r already exists") % (
            target_folder)
        sys.exit(1)

    imap.imap.rename(imap.folder_utf7(source_folder),
                     imap.folder_utf7(target_folder), partition)
Exemplo n.º 58
0
        user = conf.cli_args.pop(0)
        try:
            folder_pattern = conf.cli_args.pop(0)
        except IndexError, errmsg:
            folder_pattern = utils.ask_question(_("Folder pattern"))

    except IndexError, errmsg:
        user = utils.ask_question(_("User ID"))
        folder_pattern = utils.ask_question(_("Folder pattern"))

    if len(user.split('@')) > 1:
        domain = user.split('@')[1]
    else:
        domain = conf.get('kolab', 'primary_domain')

    imap = IMAP()
    imap.connect(domain=domain, login=False)

    backend = conf.get(domain, 'imap_backend')
    if backend == None:
        backend = conf.get('kolab', 'imap_backend')

    admin_login = conf.get(backend, 'admin_login')
    admin_password = conf.get(backend, 'admin_password')

    imap.login_plain(admin_login, admin_password, user)

    if not imap.has_folder(folder_pattern):
        print >> sys.stderr, \
                _("Cannot subscribe user to folder %r:") % (folder_pattern), \
                _("No such folder")
Exemplo n.º 59
0
def description():
    return """Obtain a list of ACL entries on a folder."""


def execute(*args, **kw):
    try:
        folder = conf.cli_args.pop(0)
    except IndexError, errmsg:
        folder = utils.ask_question(_("Folder name"))

    if len(folder.split('@')) > 1:
        domain = folder.split('@')[1]
    else:
        domain = conf.get('kolab', 'primary_domain')

    imap = IMAP()
    imap.connect(domain=domain)

    if not imap.has_folder(folder):
        print >> sys.stderr, _("No such folder %r") % (folder)

    else:
        acls = []
        folders = imap.list_folders(folder)
        for folder in folders:
            print "Folder", folder
            acls = imap.list_acls(folder)

            for acl in acls.keys():
                print "  %-13s %s" % (acls[acl], acl)