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

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

message = Chilkat::CkBinData.new()
success = message.LoadFile("message.eml")
if (success != true)
    print "Could not read message.eml." + "\n";
    exit
end

#  Supply your RSA signing key. For an encrypted PEM, get its password from your credential store.
privateKey = Chilkat::CkPrivateKey.new()
success = privateKey.LoadAnyFormatFile("dkim-private.pem","")
if (success != true)
    print privateKey.lastErrorText() + "\n";
    exit
end

signer = Chilkat::CkDkim.new()
signer.put_DkimDomain("example.com")
signer.put_DkimSelector("mail2026")
signer.put_DkimAlg("rsa-sha256")
success = signer.SetDkimPrivateKey(privateKey)
if (success != true)
    print signer.lastErrorText() + "\n";
    exit
end

#  DkimCanon takes a single setting and applies it to both headers and body.
signer.put_DkimCanon("relaxed")
signer.put_DkimHeaders("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.
signer.put_DkimBodyLengthCount(0)
success = signer.DkimSign(message)
if (success != true)
    print signer.lastErrorText() + "\n";
    exit
end

success = message.WriteFile("signed.eml")
if (success != true)
    print "Could not write signed.eml." + "\n";
    exit
end

print "Saved signed.eml." + "\n";