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])
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 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)
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
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
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)))
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)
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")
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
def check_message_received(self, subject, from_addr=None, mailbox=None): if mailbox is None: mailbox = self.john['mailbox'] imap = IMAP() imap.connect() imap.set_acl(mailbox, "cyrus-admin", "lrs") imap.imap.m.select(mailbox) found = None retries = 10 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
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)))
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})
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')
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
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()
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
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()
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
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
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])
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)
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:])))
def purge_imap(): time.sleep(2) imap = IMAP() imap.connect() for folder in imap.lm(): try: imap.dm(folder) except: pass
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()))
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)
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()
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("")
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()))
def execute(*args, **kw): """ List messages in a folder """ try: folder = conf.cli_args.pop(0) except: log.error(_("Specify a folder")) sys.exit(1) imap = IMAP() imap.connect() _folder = imap.lm(imap_utf7.encode(folder)) if _folder == None or _folder == []: log.error(_("No such folder")) sys.exit(1) imap.set_acl(folder, 'cyrus-admin', 'lrs') imap.select(imap_utf7.encode(folder)) if conf.list_deleted: typ, data = imap.search(None, 'ALL') else: typ, data = imap.search(None, '(ALL UNDELETED)') num_messages = len(data[0].split()) for num in data[0].split(): typ, flags = imap.fetch(num, 'FLAGS') flags = flags[0].split() if len(flags) >= 3: # Any flags are set if flags[2] == '(\\Deleted))': print num, '\Deleted' elif flags[2] == '(\\Deleted': print num, '\Deleted' elif '\\Deleted' in flags[3:]: print num, '\Deleted' elif '\\Deleted))' in flags[3:]: print num, '\Deleted' else: print num else: print num imap.set_acl(folder, 'cyrus-admin', '')
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()))
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)
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 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 'mailhost' not in user_info: 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 create_calendar_event(self, start=None, summary="test", sequence=0, user=None, attendees=None, folder=None): if start is None: start = datetime.datetime.now(pytz.timezone("Europe/Berlin")) if user is None: user = self.john if attendees is None: attendees = [self.jane] if folder is None: folder = user['kolabcalendarfolder'] end = start + datetime.timedelta(hours=4) event = pykolab.xml.Event() event.set_start(start) event.set_end(end) event.set_organizer(user['mail'], user['displayname']) for attendee in attendees: event.add_attendee(attendee['mail'], attendee['displayname'], role="REQ-PARTICIPANT", participant_status="NEEDS-ACTION", rsvp=True) event.set_summary(summary) event.set_sequence(sequence) # create event with attachment vattach = event.get_attachments() attachment = kolabformat.Attachment() attachment.setLabel('attach.txt') attachment.setData('This is a text attachment', 'text/plain') vattach.append(attachment) event.event.setAttachments(vattach) imap = IMAP() imap.connect() mailbox = imap.folder_quote(folder) imap.set_acl(mailbox, "cyrus-admin", "lrswipkxtecda") imap.imap.m.select(mailbox) result = imap.imap.m.append( mailbox, None, None, event.to_message().as_string() ) return event.get_uid()
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
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 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
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
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() result_attribute = conf.get('cyrus-sasl', 'result_attribute') if result_attribute is None: result_attribute = 'mail' 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: r_folder = folder if not folder.startswith('shared/'): r_folder = '/'.join(folder.split('/')[1:]) if conf.delete: if conf.dry_run: if not folder.startswith('shared/'): log.warning( _("No recipients for '%s' (would have deleted the mailbox if not for --dry-run)!" ) % (r_folder)) else: continue else: if not folder.startswith('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)!") % (r_folder))
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)
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: print >> sys.stderr, _("The quota for folder %s is set to literally allow 0KB of storage.") % (quota_folder) print "%d (Used: %d, Percentage: %s)" % (quota, used, u'\u221E') else:
"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 # so first add the right to append message (i) after adding the message
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") sys.exit(1)
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)