Sample code for 30+ languages & platforms
Lianja

Send Encrypted Email using Certificate in Apple Keychain

See more Apple Keychain Examples

Send encrypted (S/MIME) email using a certificate found in the Apple Keychain.

Note: This example requires Chilkat v10.1.2 or later.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

loEmail = createobject("CkEmail")
loEmail.Subject = "This email is encrypted"
loEmail.Body = "This is a S/MIME encrypted mail"
loEmail.From = "Joe <joe@example.com>"

// Emails are encrypted using the recipient's certificate.
lcRecipientEmailAddr = "jane@example2.com"
loEmail.AddTo("",lcRecipientEmailAddr)

// Indicate that the email is to be sent encrypted.
loEmail.SendEncrypted = .T.

loCert = createobject("CkCert")

// -----------------------------------------------
// This example requires Chilkat v10.1.2 or later.
// -----------------------------------------------

// The recipient's certificate is used to encrypt.
// This will load the certificate from the Apple Keychain.
llSuccess = loCert.LoadByEmailAddress(lcRecipientEmailAddr)
if (llSuccess <> .T.) then
    ? loCert.LastErrorText
    release loEmail
    release loCert
    return
endif

// Specify the certificate to be used for encryption.
llSuccess = loEmail.SetEncryptCert(loCert)
loEmail.SendEncrypted = .T.

loMailman = createobject("CkMailMan")
loMailman.SmtpHost = "smtp.example.com"
loMailman.SmtpUsername = "joe@example.com"
loMailman.SmtpPort = 587
loMailman.StartTLS = .T.

// We'll get the SMTP password from the Apple Keychain.
// See how we originally saved the email credentials to the Keychain here:
// Save Email Credentials in Apple Keychain or Windows Credentials Manager
loSecrets = createobject("CkSecrets")

// On Windows, this is the Windows Credentials Manager
// On MacOS/iOS, it is the Apple Keychain
loSecrets.Location = "local_manager"

// Specify the name of the secret.
// service and username are required.
// appName and domain are optional.
// Note: The values are arbitrary and can be anything you want.
loJson = createobject("CkJsonObject")
loJson.UpdateString("appName","MyEmailApp")
loJson.UpdateString("service","SMTP")
loJson.UpdateString("domain","example.com")
loJson.UpdateString("username","joe@example.com")

loMailman.SmtpPassword = loSecrets.GetSecretStr(loJson)

// Send the encrypted email.
// The email is encrypted and sent within the SendEmail function.
llSuccess = loMailman.SendEmail(loEmail)
if (llSuccess <> .T.) then
    ? loMailman.LastErrorText
    release loEmail
    release loCert
    release loMailman
    release loSecrets
    release loJson
    return
endif

? "Encrypted email sent!"


release loEmail
release loCert
release loMailman
release loSecrets
release loJson