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

Objective-C
#import <CkoEmail.h>
#import <CkoCert.h>
#import <CkoStringBuilder.h>
#import <CkoMailMan.h>

BOOL success = NO;

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

CkoEmail *email = [[CkoEmail alloc] init];

success = [email LoadEml: @"c:/temp/email/unencrypted.eml"];
if (success == NO) {
    NSLog(@"%@",email.LastErrorText);
    return;
}

// The email content is encrypted using AES with a 256-bit key, operating in GCM mode, which provides authenticated encryption.
email.Pkcs7CryptAlg = @"aes-gcm";
email.Pkcs7KeyLength = [NSNumber numberWithInt:256];
email.OaepPadding = YES;
email.OaepHash = @"sha256";
email.OaepMgfHash = @"sha256";

CkoCert *cert = [[CkoCert alloc] init];
success = [cert LoadFromFile: @"c/temps/cert/recipient.cer"];
if (success == NO) {
    NSLog(@"%@",cert.LastErrorText);
    return;
}

email.SendEncrypted = YES;
[email SetEncryptCert: cert];

CkoStringBuilder *sbSmime = [[CkoStringBuilder alloc] init];

// 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.
CkoMailMan *mailman = [[CkoMailMan alloc] init];
success = [mailman RenderToMimeSb: email renderedMime: sbSmime];
if (success == NO) {
    NSLog(@"%@",mailman.LastErrorText);
    return;
}

success = [sbSmime WriteFile: @"c:/temp/encryptedEmail.eml" charset: @"utf-8" emitBom: NO];
if (success == NO) {
    NSLog(@"%@",mailman.LastErrorText);
    return;
}

NSLog(@"%@",@"Success!");