def get_message_uids(mbox: IMAP4, label='INBOX'): """ Get all message UIDs to be fetched from server. Resume from the `latest UID` if there is one found. """ mbox.select(label, readonly=True) # mbox.select('"[Gmail]/All Mail"', readonly=True) latest_uid = MsgMeta.get_latest_uid() if latest_uid: box_status, box_data = mbox.uid('search', None, 'UID', latest_uid + ':*') else: box_status, box_data = mbox.uid('search', None, 'ALL') if box_status != OK_STATUS: return # This will be a list of bytes message_uids = box_data[0].split() if latest_uid and latest_uid.encode() in message_uids: message_uids.remove(latest_uid.encode()) log.info('Resuming from the latest UID.') log.info('Latest UID %s, Message count %s', latest_uid, len(message_uids)) return message_uids
def getLastEmails(conf, inputs, outputs): conn = IMAP(conf["mm_mail"]["server"]) conn.login(conf["mm_mail"]["user"], conf["mm_mail"]["password"]) status, data = conn.select("INBOX") results = [] for num in range(1, int(data[0]) + 1): typ, data = conn.fetch(num, '(RFC822)') raw_email = data[0][1] raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) email_from = email_message['from'] for part in email_message.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue fileName = part.get_filename() if bool(fileName): filePath = os.path.join(conf["main"]["tmpPath"], fileName) if not os.path.isfile(filePath): fp = open(filePath, 'wb') fp.write(part.get_payload(decode=True)) fp.close() results += [{"mail": email_from, "path": filePath}] conn.store(num, '+FLAGS', '\\Deleted') conn.expunge() conn.close() conn.logout() outputs["Result"]["value"] = json.dumps(results) return zoo.SERVICE_SUCCEEDED
def change_swa_settings(conn: imaplib.IMAP4, swa_options: dict): """Changes swa preference email or create a new one if message with preference does not exists. :param swa_options: :param conn: imaplib.IMAP4 :return: """ status, data = conn.select('#Scalix/Oddpost') if status != 'OK': raise Exception('Could not select folder #Scalix/Oddpost. ' 'Imap response: {}'.format(data)) orphan_uids = set() if not int(data[0]): # there are no messages in mailbox fetching will fail so we will # skip it email = create_preference_message() else: email, orphan_uids = find_swa_preference_email(conn) if not email: email = create_preference_message() # lets apply changes to the preferences for key, value in swa_options.items(): find_option_and_change(email.preferences, key, value) # if we have UID for previous email jus tadd it to delete if email.uid: orphan_uids.add(email.uid) if orphan_uids: uids_del = b','.join([str(uid).encode() for uid in orphan_uids]) status, data = conn.uid('STORE', uids_del.decode(), '+FLAGS', '\\Deleted') if status != 'OK': warnings.warn( 'Could not delete duplicate preference emails {}' '. Error {}.'.format(orphan_uids, data), RuntimeWarning ) status, data = conn.append('#Scalix/Oddpost', '\\Seen', imaplib.Time2Internaldate(time.time()), email.as_bytes()) if status != 'OK': if email.uid: conn.uid('STORE', email.uid, '-FLAGS', '\\Deleted') raise Exception('Could not save email. Error message {}'.format(data)) conn.expunge()
def run(self, imap_obj: imaplib.IMAP4): """Executes EXAMINE Imap command for a specified folder and parses response from an server response. Raises: ImapRuntimeError - if command executions failed :param imap_obj: imaplib.IMAP4 :return: dict """ status, data = imap_obj.select(self.__folder, readonly=self.__readonly) self.check_response(status, data) result = {'EXISTS': int(data[0])} for attr in FOLDER_UNTAGGED_KEYS: value = self.untagged_value(imap_obj, attr) if value: if value and attr in ('PERMANENTFLAGS', 'FLAGS'): value = value.strip(b'()').split(b' ') else: value = int(value) result[attr] = value return result
def __select_mailbox(self, imap_connection: IMAP4) -> None: selection_result, _ = imap_connection.select(self.__config.mailbox) ImapConnectionHandler.validate_selection_result(selection_result)