Sample code for 30+ languages & platforms
CkPython 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 CkPython Downloads

CkPython
import sys
import chilkat

success = False

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

email = chilkat.CkEmail()
success = email.LoadEml("with-attachments.eml")
if (success != True):
    print(email.lastErrorText())
    sys.exit()

signer = chilkat.CkCert()
success = signer.LoadPfxFile("signer.pfx","SIGNER_PASSWORD")
if (success != True):
    print(signer.lastErrorText())
    sys.exit()

recipient = chilkat.CkCert()
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.put_SigningHashAlg("sha256")
email.put_Pkcs7CryptAlg("aes")
email.put_Pkcs7KeyLength(256)
email.put_OaepPadding(True)
email.put_OaepHash("sha256")
email.put_OaepMgfHash("sha256")
email.put_SendSigned(True)
email.put_SendEncrypted(True)
mail = chilkat.CkMailMan()
rendered = chilkat.CkBinData()
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.")