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

Unicode C++
#include <CkEmailW.h>
#include <CkCertW.h>
#include <CkMailManW.h>
#include <CkBinDataW.h>

void ChilkatSample(void)
    {
    bool success = false;

    //  Assumes Chilkat is unlocked. See Global Unlock Sample.

    CkEmailW email;
    success = email.LoadEml(L"with-attachments.eml");
    if (success != true) {
        wprintf(L"%s\n",email.lastErrorText());
        return;
    }

    CkCertW signer;
    success = signer.LoadPfxFile(L"signer.pfx",L"SIGNER_PASSWORD");
    if (success != true) {
        wprintf(L"%s\n",signer.lastErrorText());
        return;
    }

    CkCertW recipient;
    success = recipient.LoadFromFile(L"recipient.cer");
    if (success != true) {
        wprintf(L"%s\n",recipient.lastErrorText());
        return;
    }

    success = email.SetSigningCert(signer);
    if (success != true) {
        wprintf(L"%s\n",email.lastErrorText());
        return;
    }

    success = email.SetEncryptCert(recipient);
    if (success != true) {
        wprintf(L"%s\n",email.lastErrorText());
        return;
    }

    email.put_SigningHashAlg(L"sha256");
    email.put_Pkcs7CryptAlg(L"aes");
    email.put_Pkcs7KeyLength(256);
    email.put_OaepPadding(true);
    email.put_OaepHash(L"sha256");
    email.put_OaepMgfHash(L"sha256");
    email.put_SendSigned(true);
    email.put_SendEncrypted(true);
    CkMailManW mail;
    CkBinDataW rendered;
    success = mail.RenderToMimeBd(email,rendered);
    if (success != true) {
        wprintf(L"%s\n",mail.lastErrorText());
        return;
    }

    success = rendered.WriteFile(L"signed-encrypted.eml");
    if (success != true) {
        wprintf(L"Failed: rendered.WriteFile.\n");
        return;
    }

    wprintf(L"Saved signed-encrypted.eml.\n");
    }