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

Lua
local chilkat = require("chilkat")

-- Assumes Chilkat is unlocked. See Global Unlock Sample.

local message = chilkat.BinData.new()
local success = message:load_file("message.eml")
if not success then
    print("Could not read message.eml.")
    return
end

-- Supply your RSA signing key. For an encrypted PEM, get its password from your credential store.
local privateKey = chilkat.PrivateKey.new()
success = privateKey:load_any_format_file("dkim-private.pem", "")
if not success then
    print(privateKey.last_error_text)
    return
end

local signer = chilkat.Dkim.new()
signer.dkim_domain = "example.com"
signer.dkim_selector = "mail2026"
signer.dkim_alg = "rsa-sha256"
success = signer:set_dkim_private_key(privateKey)
if not success then
    print(signer.last_error_text)
    return
end

-- DkimCanon takes a single setting and applies it to both headers and body.
signer.dkim_canon = "relaxed"
signer.dkim_headers = "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.dkim_body_length_count = 0
success = signer:dkim_sign(message)
if not success then
    print(signer.last_error_text)
    return
end

success = message:write_file("signed.eml")
if not success then
    print("Could not write signed.eml.")
    return
end

print("Saved signed.eml.")