def get_message_ids(client, folder): try: client.select_folder(folder) msg_ids = client.search() return msg_ids except Exception as e: logger.error("Could not get message id: %r", e) return []
def delete(client, folder): try: client.select(folder) typ, data = client.search(None, 'ALL') for num in data[0].split(): client.store(num, '+FLAGS', '\\Deleted') client.expunge() except Exception as e: logger.error("Could not delete message: %r", e) return False
def send_message(client, payload, folder_name=None): try: if not folder_name: folder_name = "Sent" client.select_folder(folder_name) client.append(folder_name, payload, flags=(SEEN, SENT_FROM_WEBMAIL)) return True except Exception as e: logger.error("Could not create new message: %r", e) return False
def login(client): """Login client using username and password client is IMAPClient instance """ try: client.login(ImapConfig.user, ImapConfig.password) return True except Exception as e: logger.error("Could not login") return False
def new_imap_client(): """Connect to imap server. Return imapclient instance or None if any exception occurs """ try: client = IMAPClient(ImapConfig.host, ImapConfig.port, ssl=False) client.starttls() return client except Exception as e: logger.error("Failed to connect to imap server")
def new_message(client, folder="Drafts", flags=(DRAFT, DRAFT_FROM_WEBMAIL)): try: uniq_id = generate_message_id() body = f"Message-ID: {uniq_id}" client.select_folder(folder) client.append(folder, body, flags=flags) res = client.search( SEARCH_CRITERIA_BY_MESSAGE_HEADER_ID.format(uniq_id)) return res[0], uniq_id except Exception as e: logger.error("Could not create new message: %r", e) return False
def login(client, username, password): """Login client using username and password client is IMAPClient instance """ try: client.login(username, password) return True except Exception as e: logger.error("Could not login: %r", e) return False
def remove_flags(client, folder, message_ids, flags): """ message_ids: list of message imap id flags: list of IMAP flags, \Seen \Answered \Flagged \Deleted \Draft \Recent or custom keywords """ try: client.select_folder(folder) client.remove_flags(message_ids, flags) return True except Exception as e: logger.error("Could not set flag for message: %r", e) return False
def new_imap_client(host, port=143, ssl=False): """Connect to imap server. Return imapclient instance or None if any exception occurs """ try: client = IMAPClient(host, port=port, ssl=ssl) if not ssl: client.starttls() return client except Exception as e: logger.error( "Failed to connect to imap server: %s:%s, reason: %r", host, port, e, )