Ejemplo n.º 1
0
def _build_mail_to_encrypt(message: str, files: list) -> MIMEMultipart:
    """
    Create the MIMEMultipart mail containing the text message and the potentials attachments.

    :param message: The text message of the encrypted email.
    :param files: The files to attach and encrypt.
    :return: A MIMEMultipart mail object.
    """
    mail_to_encrypt = MIMEMultipart()
    mail_to_encrypt.policy = policy.SMTPUTF8
    if message == '--':
        message = sys.stdin.read()

    message_mail = MIMEBase('text', 'plain', charset='UTF-8')
    message_mail.policy = policy.SMTPUTF8
    message_mail.set_payload(message.encode('UTF-8'))
    encoders.encode_quopri(message_mail)
    mail_to_encrypt.attach(message_mail)

    if files:
        for file in files:
            path = Path(file)

            guessed_type = mimetypes.guess_type(path.absolute().as_uri())[0]

            if not guessed_type:
                print('Could not guess file %s mime-type, using application/octet-stream.' % file, file=sys.stderr)
                guessed_type = 'application/octet-stream'

            mimetype = guessed_type.split('/')

            mail_attachment = MIMEBase(mimetype[0], mimetype[1])
            mail_attachment.policy = policy.SMTPUTF8
            mail_attachment.set_payload(open(str(path.absolute()), 'rb').read())
            encoders.encode_base64(mail_attachment)
            mail_attachment.add_header('Content-Disposition', "attachment", filename=path.name)

            mail_to_encrypt.attach(mail_attachment)

    return mail_to_encrypt