Sample code for 30+ languages & platforms
Tcl Requires Chilkat v11.0.0+

Sign a saved MIME message with DKIM

See more DKIM Examples

Sign the complete bytes of message.eml and save the result as signed.eml. Finish the message’s From, To, Date, Message-ID, MIME parts and transfer encodings before signing. Existing signatures stay in place and the new signature is inserted first.

The example signs the full body and includes From in the signed headers. Relaxed canonicalization tolerates defined whitespace and header folding changes. Editing a signed field or changing the body text can still break verification. Prepare the matching DNS record.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

set message [new_CkBinData]

set success [CkBinData_LoadFile $message "message.eml"]
if {$success != 1} then {
    puts "Could not read message.eml."
    delete_CkBinData $message
    exit
}

#  Supply your RSA signing key. For an encrypted PEM, get its password from your credential store.
set privateKey [new_CkPrivateKey]

set success [CkPrivateKey_LoadAnyFormatFile $privateKey "dkim-private.pem" ""]
if {$success != 1} then {
    puts [CkPrivateKey_lastErrorText $privateKey]
    delete_CkBinData $message
    delete_CkPrivateKey $privateKey
    exit
}

set signer [new_CkDkim]

CkDkim_put_DkimDomain $signer "example.com"
CkDkim_put_DkimSelector $signer "mail2026"
CkDkim_put_DkimAlg $signer "rsa-sha256"
set success [CkDkim_SetDkimPrivateKey $signer $privateKey]
if {$success != 1} then {
    puts [CkDkim_lastErrorText $signer]
    delete_CkBinData $message
    delete_CkPrivateKey $privateKey
    delete_CkDkim $signer
    exit
}

#  DkimCanon takes a single setting and applies it to both headers and body.
CkDkim_put_DkimCanon $signer "relaxed"
CkDkim_put_DkimHeaders $signer "from:to:subject:date:message-id:mime-version:content-type:content-transfer-encoding"
#  Zero signs the entire canonicalized body and omits the optional l= tag.
CkDkim_put_DkimBodyLengthCount $signer 0
set success [CkDkim_DkimSign $signer $message]
if {$success != 1} then {
    puts [CkDkim_lastErrorText $signer]
    delete_CkBinData $message
    delete_CkPrivateKey $privateKey
    delete_CkDkim $signer
    exit
}

set success [CkBinData_WriteFile $message "signed.eml"]
if {$success != 1} then {
    puts "Could not write signed.eml."
    delete_CkBinData $message
    delete_CkPrivateKey $privateKey
    delete_CkDkim $signer
    exit
}

puts "Saved signed.eml."

delete_CkBinData $message
delete_CkPrivateKey $privateKey
delete_CkDkim $signer