Sample code for 30+ languages & platforms
PowerBuilder

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 PowerBuilder Downloads

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Email
oleobject loo_Cert
oleobject loo_SbSmime
oleobject loo_Mailman

li_Success = 0

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

loo_Email = create oleobject
li_rc = loo_Email.ConnectToNewObject("Chilkat.Email")
if li_rc < 0 then
    destroy loo_Email
    MessageBox("Error","Connecting to COM object failed")
    return
end if

li_Success = loo_Email.LoadEml("c:/temp/email/unencrypted.eml")
if li_Success = 0 then
    Write-Debug loo_Email.LastErrorText
    destroy loo_Email
    return
end if

// The email content is encrypted using AES with a 256-bit key, operating in GCM mode, which provides authenticated encryption.
loo_Email.Pkcs7CryptAlg = "aes-gcm"
loo_Email.Pkcs7KeyLength = 256
loo_Email.OaepPadding = 1
loo_Email.OaepHash = "sha256"
loo_Email.OaepMgfHash = "sha256"

loo_Cert = create oleobject
li_rc = loo_Cert.ConnectToNewObject("Chilkat.Cert")

li_Success = loo_Cert.LoadFromFile("c/temps/cert/recipient.cer")
if li_Success = 0 then
    Write-Debug loo_Cert.LastErrorText
    destroy loo_Email
    destroy loo_Cert
    return
end if

loo_Email.SendEncrypted = 1
loo_Email.SetEncryptCert(loo_Cert)

loo_SbSmime = create oleobject
li_rc = loo_SbSmime.ConnectToNewObject("Chilkat.StringBuilder")

// 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.
loo_Mailman = create oleobject
li_rc = loo_Mailman.ConnectToNewObject("Chilkat.MailMan")

li_Success = loo_Mailman.RenderToMimeSb(loo_Email,loo_SbSmime)
if li_Success = 0 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_Email
    destroy loo_Cert
    destroy loo_SbSmime
    destroy loo_Mailman
    return
end if

li_Success = loo_SbSmime.WriteFile("c:/temp/encryptedEmail.eml","utf-8",0)
if li_Success = 0 then
    Write-Debug loo_Mailman.LastErrorText
    destroy loo_Email
    destroy loo_Cert
    destroy loo_SbSmime
    destroy loo_Mailman
    return
end if

Write-Debug "Success!"


destroy loo_Email
destroy loo_Cert
destroy loo_SbSmime
destroy loo_Mailman