Skip to content

Documentation: Add an example how to sign/encrypt/sign and encrypt an email #12657

@dirkgomez

Description

@dirkgomez

9 andhttps://github.com//issues/10664, both of which seem to have not really been resolved.

My assumption is: it is possible to sign/encrypt/sign and encrypt emails with cryptography, sources: https://m2crypto.readthedocs.io/en/latest/howto.migration.html#signing or https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.pkcs7.PKCS7EnvelopeBuilder

Yet I'm struggling to properly send encrypted emails with cryptography and Python standard modules. The building blocks are there, I can encrypt and send emails, yet the result isn't production ready:

  • they contain headers and the content-type information
  • long lines are broken up into multiple lines
  • no subject

Here's how my code currently looks like:

    message["Subject"] = subject
    message["To"] = recipient
    message["From"] = from
    message["Sender"] = sender

    message.set_content(content)
    if attachments:

        for attachment in attachments:
            message.add_attachment(
                base64.b64decode(attachment.content),
                maintype="application",
                subtype="octet-stream",
                filename=attachment.name,
            )

    options = [pkcs7.PKCS7Options.Text]
    encrypted_content = (
        pkcs7.PKCS7EnvelopeBuilder()
        .set_data(message.as_bytes())
        .add_recipient(certificate)
        .encrypt(serialization.Encoding.SMIME, options)
    )

    encrypted_message = BytesParser().parsebytes(encrypted_content)

    encrypted_message["Subject"] = subject
    encrypted_message.set_payload(encrypted_content)

It would be great to have an authoritative example how to send encrypted emails with cryptography, there are a lot of outdated examples for deprecated packages on the internet each making the world a little less safe.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions