Sample code for 30+ languages & platforms
Python Requires Chilkat v11.0.0+

Sign and encrypt an email with S/MIME

See more Email Object Examples

Use the sender’s signing PFX and the recipient’s public RSA certificate with with-attachments.eml, which has one recipient. Supply your own signing-key password from a credential store. Render to bytes to apply both S/MIME operations without connecting to SMTP.

Chilkat Python Downloads

Python
import sys
import chilkat2

success = False

# Assumes Chilkat is unlocked. See Global Unlock Sample.

email = chilkat2.Email()
success = email.LoadEml("with-attachments.eml")
if (success != True):
    print(email.LastErrorText)
    sys.exit()

signer = chilkat2.Cert()
success = signer.LoadPfxFile("signer.pfx","SIGNER_PASSWORD")
if (success != True):
    print(signer.LastErrorText)
    sys.exit()

recipient = chilkat2.Cert()
success = recipient.LoadFromFile("recipient.cer")
if (success != True):
    print(recipient.LastErrorText)
    sys.exit()

success = email.SetSigningCert(signer)
if (success != True):
    print(email.LastErrorText)
    sys.exit()

success = email.SetEncryptCert(recipient)
if (success != True):
    print(email.LastErrorText)
    sys.exit()

email.SigningHashAlg = "sha256"
email.Pkcs7CryptAlg = "aes"
email.Pkcs7KeyLength = 256
email.OaepPadding = True
email.OaepHash = "sha256"
email.OaepMgfHash = "sha256"
email.SendSigned = True
email.SendEncrypted = True
mail = chilkat2.MailMan()
rendered = chilkat2.BinData()
success = mail.RenderToMimeBd(email,rendered)
if (success != True):
    print(mail.LastErrorText)
    sys.exit()

success = rendered.WriteFile("signed-encrypted.eml")
if (success != True):
    print("Failed: rendered.WriteFile.")
    sys.exit()

print("Saved signed-encrypted.eml.")