Example #1
0
    def __try_download_attachments_to_path(
            self, imap_connection: IMAP4,
            email_data: List[Tuple[bytes, bytes]]) -> None:
        ImapConnectionHandler.__email_data_has_bytes(email_data)
        for i, mail in enumerate(email_data[0].split()):
            _, email_bytes_tuple = imap_connection.fetch(mail, '(RFC822)')
            email_message = ImapConnectionHandler.__get_email_message_from_bytes_tuple(
                email_bytes_tuple)

            for part in email_message.walk():
                file_path: str

                if part.get_content_maintype(
                ) == 'multipart' or part.get('Content-Disposition') is None:
                    continue

                if os.path.exists(
                        f'{self.__config.save_file_path}/{part.get_filename()}'
                ):
                    file_and_extension_split = part.get_filename().split(".")
                    attachment_name, extension = file_and_extension_split[
                        0], file_and_extension_split[1]
                    file_path = '{}/{}_{}.{}'.format(
                        self.__config.save_file_path, attachment_name, i,
                        extension)
                else:
                    file_path = '{}/{}'.format(self.__config.save_file_path,
                                               part.get_filename())

                IOHandler.save_email_attachment(
                    part, part.get('Content-Disposition'), file_path)
Example #2
0
    def __try_write_message_body_to_file(
            self, imap_connection: IMAP4,
            email_data: List[Tuple[bytes, bytes]]) -> None:
        ImapConnectionHandler.__email_data_has_bytes(email_data)
        for i, mail in enumerate(email_data[0].split()):
            file_path = '{}/{}_{}.{}'.format(self.__config.save_file_path,
                                             self.__config.save_file_name, i,
                                             self.__config.extension)
            _, email_bytes_tuple = imap_connection.fetch(mail, '(RFC822)')

            if email_bytes_tuple[0] is not None:
                IOHandler.truncate_file_content(file_path)
                email_message = ImapConnectionHandler.__get_email_message_from_bytes_tuple(
                    email_bytes_tuple)

                if email_message.is_multipart():
                    for part in email_message.walk():
                        IOHandler.write_payload_to_file(
                            payload=part.get_payload(decode=True),
                            content_type=part.get_content_type(),
                            content_disposition=str(
                                part.get('Content-Disposition')),
                            file_path=file_path)
                else:
                    IOHandler.write_payload_to_file(
                        payload=email_message.get_payload(decode=True),
                        content_type=email_message.get_content_type(),
                        content_disposition=str(
                            email_message.get('Content-Disposition')),
                        file_path=file_path)
            else:
                print('No information was found for the searched message')
Example #3
0
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
Example #4
0
def fetch_mail(imap: IMAP4, num):
    typ, data = imap.fetch(num, '(RFC822)')
    if typ != 'OK':
        raise Exception('Could not fetch the specified mail')
    raw_email = data[0]
    if raw_email is None or isinstance(raw_email, bytes):
        raise Exception('I expected raw_email part to be a tuple.'
                        ' Rewrite your fetching code.')
    msg = email.message_from_bytes(raw_email[1])
    return msg
Example #5
0
 def __send_email_data_with_smtp(self, imap_connection: IMAP4,
                                 email_data: List[Tuple[bytes, bytes]]):
     ImapConnectionHandler.__email_data_has_bytes(email_data)
     list_of_email_messages = []
     for i, mail in enumerate(email_data[0].split()):
         _, email_bytes_tuple = imap_connection.fetch(mail, '(RFC822)')
         list_of_email_messages.append(
             ImapConnectionHandler.__get_email_message_from_bytes_tuple(
                 email_bytes_tuple))
     self.__smtp_connection_handler.send_email_data_to_config_addresses(
         list_of_email_messages)
Example #6
0
def get_msg_headers(server: imaplib.IMAP4,
                    msg_ids: List[int]) -> List[Tuple[int, bytes]]:
    """
    Get the dict of headers for each message in the list of provided IDs.
    Return a list of tuples:  [ (msgid, header_bytes), (msgid, header_bytes)... ]
    The returned header_bytes can be parsed by 
    """
    # Get the header info for each message
    message_ids_str = ",".join(map(str, msg_ids))
    ms = check_response(server.fetch(message_ids_str, "(RFC822.HEADER)"))

    # There are two lines per message in the response
    resp: List[Tuple[int, bytes]] = []
    for ci in range(len(ms) // 2):
        mnum = int(msg_ids[ci])
        _, hinfo = ms[ci * 2]
        resp.append((mnum, hinfo))
    return resp
def fetch_mail(mail_id, server_conn: imaplib.IMAP4):
    if type(mail_id) == str or type(mail_id) == str:
        return server_conn.fetch(str(mail_id), '(RFC822)')
    elif type(mail_id) == Email:
        return server_conn.fetch(mail_id.id, '(RFC822)')