Sample code for 30+ languages & platforms
Unicode C

S/MIME Encrypt .eml without Sending

See more Email Object Examples

Demonstrates how to encrypt an email using the recipient's digital certificate. This example just encrypts, and does not send the email.

Chilkat Unicode C Downloads

Unicode C
#include <C_CkEmailW.h>
#include <C_CkCertW.h>
#include <C_CkStringBuilderW.h>
#include <C_CkMailManW.h>

void ChilkatSample(void)
    {
    BOOL success;
    HCkEmailW email;
    HCkCertW cert;
    HCkStringBuilderW sbSmime;
    HCkMailManW mailman;

    success = FALSE;

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    email = CkEmailW_Create();

    success = CkEmailW_LoadEml(email,L"c:/temp/email/unencrypted.eml");
    if (success == FALSE) {
        wprintf(L"%s\n",CkEmailW_lastErrorText(email));
        CkEmailW_Dispose(email);
        return;
    }

    // The email content is encrypted using AES with a 256-bit key, operating in GCM mode, which provides authenticated encryption.
    CkEmailW_putPkcs7CryptAlg(email,L"aes-gcm");
    CkEmailW_putPkcs7KeyLength(email,256);
    CkEmailW_putOaepPadding(email,TRUE);
    CkEmailW_putOaepHash(email,L"sha256");
    CkEmailW_putOaepMgfHash(email,L"sha256");

    cert = CkCertW_Create();
    success = CkCertW_LoadFromFile(cert,L"c/temps/cert/recipient.cer");
    if (success == FALSE) {
        wprintf(L"%s\n",CkCertW_lastErrorText(cert));
        CkEmailW_Dispose(email);
        CkCertW_Dispose(cert);
        return;
    }

    CkEmailW_putSendEncrypted(email,TRUE);
    CkEmailW_SetEncryptCert(email,cert);

    sbSmime = CkStringBuilderW_Create();

    // The mailman object applies the encryption by rendering the email according to the instructions (property settings) provided in the email object.
    // No email is sent.
    mailman = CkMailManW_Create();
    success = CkMailManW_RenderToMimeSb(mailman,email,sbSmime);
    if (success == FALSE) {
        wprintf(L"%s\n",CkMailManW_lastErrorText(mailman));
        CkEmailW_Dispose(email);
        CkCertW_Dispose(cert);
        CkStringBuilderW_Dispose(sbSmime);
        CkMailManW_Dispose(mailman);
        return;
    }

    success = CkStringBuilderW_WriteFile(sbSmime,L"c:/temp/encryptedEmail.eml",L"utf-8",FALSE);
    if (success == FALSE) {
        wprintf(L"%s\n",CkMailManW_lastErrorText(mailman));
        CkEmailW_Dispose(email);
        CkCertW_Dispose(cert);
        CkStringBuilderW_Dispose(sbSmime);
        CkMailManW_Dispose(mailman);
        return;
    }

    wprintf(L"Success!\n");


    CkEmailW_Dispose(email);
    CkCertW_Dispose(cert);
    CkStringBuilderW_Dispose(sbSmime);
    CkMailManW_Dispose(mailman);

    }