Skip to content

Request: Add example how to sign a mail #11489

Closed
@ikreb7

Description

@ikreb7

Hello,

I try to sign a mail with cryptography but I have still problems. There was the issue #4488. But at that time, S/MIME support was not yet so advanced.

This is my code, but I have still the problem, that Thunderbird show that the mail isn't signed and outlook shows that the mail is signed, but don't open the mail.

import smtplib
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr, formatdate, parseaddr

from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.serialization import pkcs7

from_addr = "[email protected]"
to_addr = "[email protected]"

message = MIMEMultipart()
message["Subject"] = Header("Signed Mail", "utf-8").encode()
message["From"] = formataddr(parseaddr(f"Github <{from_addr}>"))
message["To"] = to_addr
message["Date"] = formatdate(localtime=True)
message["Auto-Submitted"] = "auto-generated"
message.preamble = "This is an S/MIME signed message"

body = "This a plain text body!"
message.attach(MIMEText(body, "utf-8"))

ca_cert = open("cert.pem", "rb").read()
ca_key = open("key.pem", "rb").read()

cert = x509.load_pem_x509_certificate(ca_cert)
key = serialization.load_pem_private_key(ca_key, None)
options = [pkcs7.PKCS7Options.DetachedSignature]

signed_message = (
    pkcs7.PKCS7SignatureBuilder()
    .set_data(message.as_bytes())
    .add_signer(cert, key, hashes.SHA256())
    .sign(serialization.Encoding.SMIME, options)
)

server_name = "localhost"
with smtplib.SMTP() as server:
    server.set_debuglevel(True)
    server.connect(server_name, port=25)
    server.sendmail(from_addr, to_addr, signed_message)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions