Signing Emails with DKIM for Authentication and Deliverability in Java
DKIM (DomainKeys Identified Mail, RFC 6376) lets a domain owner attach a cryptographic signature to outgoing email. Receiving servers fetch the matching public key from DNS, recompute the hash, and confirm two things at once: the message body was not modified in transit, and the message really originated from a sender authorized by the domain. Without DKIM, modern providers (Gmail, Microsoft 365, Yahoo) flag mail as spam, drop it silently, or refuse delivery — DKIM is no longer optional for production mail.
This guide is a complete walkthrough of the DKIM API of Aspose.Email for Java.
Prerequisites
You need an RSA key pair. The private key is held in your application and used to sign; the public key is published as a DNS TXT record so receivers can verify. A 2048-bit key is the standard today:
openssl genrsa -out sample-private-key.pem 2048
PemReader accepts both PKCS#1 (-----BEGIN RSA PRIVATE KEY-----) and PKCS#8 (-----BEGIN PRIVATE KEY-----) formatted files.
| Class | Role |
|---|---|
| DKIMSignatureInfo | Describes the signature: selector, domain, hash algorithm, canonicalization, and which headers to cover. |
| PemReader | Loads an RSA private key from a PEM-formatted file or stream into a java.security.PrivateKey. |
MailMessage.dKIMSign(key, info) |
Returns a signed copy of the message with the DKIM-Signature header populated. |
| DkimVerifier | Performs DNS-based verification of a signed message — from a file or a stream. |
The full flow is always: load key → describe signature → build message → sign → (optionally) verify.
The Minimal Signing Example
This is the smallest amount of code that produces a valid DKIM-signed message:
// Load the private key from a PEM file
PrivateKey privateKey = PemReader.getPrivateKey("sample-private-key.pem");
// Create the DKIM signature information
// Default: Relaxed/Relaxed canonicalization, RSASha1 hash algorithm
DKIMSignatureInfo signInfo = new DKIMSignatureInfo("dkim", "example.com");
// Add the headers to sign
signInfo.getHeaders().addItem("From");
signInfo.getHeaders().addItem("To");
signInfo.getHeaders().addItem("Subject");
// Create a test email
MailMessage mailMessage = new MailMessage(
"sender@example.com",
"recipient@example.com",
"Test Subject",
"This is a test email body signed with DKIM.");
mailMessage.setFrom(new MailAddress("sender@example.com", "Sender Name"));
// Sign the message
MailMessage signedMsg = mailMessage.dKIMSign(privateKey, signInfo);
// Save the signed message
signedMsg.save("basic-signed.eml");
System.out.println("DKIM-Signature header: " + signedMsg.getHeaders().get_Item("DKIM-Signature"));
The two arguments to DKIMSignatureInfo — "dkim" and "example.com" — are the selector and the domain. Together they tell receivers where to look up your public key: at the DNS TXT record dkim._domainkey.example.com. Pick a short selector name (often default, mail, or a date like 2026jan); the selector lets you rotate keys without throwing away the old one.
A critical detail: dKIMSign returns a new MailMessage instance with the DKIM-Signature header added. The original message is unchanged. Save or send the returned object, not the input.
Choosing Which Headers to Sign
The headers listed in signInfo.getHeaders() are the only ones whose values are bound to the signature. Anything not listed can be modified by relays without breaking the signature, which is sometimes desirable (e.g. Received: headers added downstream) and sometimes dangerous (e.g. leaving From unsigned makes the signature meaningless).
Rule of thumb: always sign From, To, Subject, Date. From in particular is mandatory for DMARC alignment.
PrivateKey privateKey = PemReader.getPrivateKey("sample-private-key.pem");
DKIMSignatureInfo signInfo = new DKIMSignatureInfo("dkim2", "example.com");
signInfo.getHeaders().addItem("From");
signInfo.getHeaders().addItem("To");
signInfo.getHeaders().addItem("Subject");
signInfo.getHeaders().addItem("Date");
signInfo.getHeaders().addItem("MIME-Version");
// Create the email with additional headers
MailMessage mailMessage = new MailMessage(
"sender@example.com",
"recipient@example.com",
"Custom Headers Test",
"This message includes custom headers in the DKIM signature.");
mailMessage.setFrom(new MailAddress("sender@example.com", "Sender"));
mailMessage.setDate(new Date());
// Make sure the headers listed in the DKIM signature are present on the message
mailMessage.getHeaders().add("MIME-Version", "1.0");
mailMessage.getHeaders().add("X-Custom-Header", "CustomValue");
MailMessage signedMsg = mailMessage.dKIMSign(privateKey, signInfo);
signedMsg.save("custom-headers-signed.eml");
If you list Date but never call mailMessage.setDate(...), signing fails with The following headers to be signed do not exist: Date. Always populate the headers first, then sign.
Hash Algorithms — RSA-SHA1 vs RSA-SHA256
DKIM supports two signing algorithms. The default in Aspose.Email is RSASha1 for backwards compatibility, but every new deployment should use RSASha256. Many providers now mark SHA-1 signatures as invalid even when they verify cryptographically.
PrivateKey privateKey = PemReader.getPrivateKey("sample-private-key.pem");
// Example with RSASha1 (older, less secure but widely supported)
DKIMSignatureInfo signInfoSha1 = new DKIMSignatureInfo("dkim-sha1", "example.com");
signInfoSha1.setHashAlgorithm(DKIMHashAlgorithm.RSASha1);
signInfoSha1.getHeaders().addItem("From");
signInfoSha1.getHeaders().addItem("To");
signInfoSha1.getHeaders().addItem("Subject");
MailMessage mailMessage1 = new MailMessage(
"sender@example.com", "recipient@example.com", "SHA1 Test", "Signed with the RSASha1 algorithm.");
mailMessage1.setFrom(new MailAddress("sender@example.com"));
mailMessage1.dKIMSign(privateKey, signInfoSha1).save("sha1-signed.eml");
// Example with RSASha256 (newer, more secure)
DKIMSignatureInfo signInfoSha256 = new DKIMSignatureInfo("dkim-sha256", "example.com");
signInfoSha256.setHashAlgorithm(DKIMHashAlgorithm.RSASha256);
signInfoSha256.getHeaders().addItem("From");
signInfoSha256.getHeaders().addItem("To");
signInfoSha256.getHeaders().addItem("Subject");
MailMessage mailMessage2 = new MailMessage(
"sender@example.com", "recipient@example.com", "SHA256 Test", "Signed with the RSASha256 algorithm.");
mailMessage2.setFrom(new MailAddress("sender@example.com"));
mailMessage2.dKIMSign(privateKey, signInfoSha256).save("sha256-signed.eml");
The resulting DKIM-Signature header advertises the algorithm via the a= tag (a=rsa-sha1 vs a=rsa-sha256). Receivers consult that tag to decide which hash to recompute.
Canonicalization — Simple vs Relaxed
Canonicalization is how DKIM agrees on a stable, byte-exact form of the message before hashing. Two algorithms are defined for headers and bodies independently:
Simple— almost no normalization. Trailing empty lines in the body are removed, but no other whitespace is touched. A single space added by a relay will invalidate the signature.Relaxed— folds whitespace inside header values, lowercases header names, and collapses runs of whitespace in the body. Tolerant of the trivial reformatting that mail transport agents tend to do.
Choose Relaxed for both header and body unless you have a specific reason not to. Almost every production deployment does.
PrivateKey privateKey = PemReader.getPrivateKey("sample-private-key.pem");
// Simple canonicalization - almost no changes allowed
DKIMSignatureInfo signInfoSimple = new DKIMSignatureInfo("dkim-simple", "example.com");
signInfoSimple.setHeaderCanonicalization(CanonicalizationType.Simple);
signInfoSimple.setBodyCanonicalization(CanonicalizationType.Simple);
signInfoSimple.getHeaders().addItem("From");
signInfoSimple.getHeaders().addItem("To");
signInfoSimple.getHeaders().addItem("Subject");
MailMessage mailMessage1 = new MailMessage(
"sender@example.com", "recipient@example.com",
"Simple Canonicalization", "This message uses Simple canonicalization.");
mailMessage1.setFrom(new MailAddress("sender@example.com"));
mailMessage1.dKIMSign(privateKey, signInfoSimple).save("simple-canonical.eml");
// Relaxed canonicalization - minor changes allowed (whitespace normalization)
DKIMSignatureInfo signInfoRelaxed = new DKIMSignatureInfo("dkim-relaxed", "example.com");
signInfoRelaxed.setHeaderCanonicalization(CanonicalizationType.Relaxed);
signInfoRelaxed.setBodyCanonicalization(CanonicalizationType.Relaxed);
signInfoRelaxed.getHeaders().addItem("From");
signInfoRelaxed.getHeaders().addItem("To");
signInfoRelaxed.getHeaders().addItem("Subject");
MailMessage mailMessage2 = new MailMessage(
"sender@example.com", "recipient@example.com",
"Relaxed Canonicalization", "This message uses Relaxed canonicalization.");
mailMessage2.setFrom(new MailAddress("sender@example.com"));
mailMessage2.dKIMSign(privateKey, signInfoRelaxed).save("relaxed-canonical.eml");
Header and body canonicalization are independent — relaxed/simple is a perfectly valid combination, written that way in the c= tag of the DKIM header.
Loading the Private Key
PemReader handles both PEM encodings transparently. There is no separate PKCS#1 / PKCS#8 reader — just pass the path or a stream:
// From a file
PrivateKey fromFile = PemReader.getPrivateKey("sample-private-key.pem");
// From a stream - a key vault, an encrypted blob, or an embedded resource
try (InputStream keyStream = Files.newInputStream(Paths.get("sample-private-key.pem"))) {
PrivateKey fromStream = PemReader.getPrivateKey(keyStream);
System.out.println(fromStream.getAlgorithm());
}
System.out.println(fromFile.getAlgorithm());
A PEM file contains either of the following:
-----BEGIN RSA PRIVATE KEY----- (PKCS#1)
MIIEpAIBAAKCAQEA0Z3VS5JJcds3xfn/ygWyF8PbnGy...
-----END RSA PRIVATE KEY-----
-----BEGIN PRIVATE KEY----- (PKCS#8)
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC...
-----END PRIVATE KEY-----
Key handling rules:
- Never commit private keys to version control.
*.pembelongs in.gitignore. - In production, load keys from a secrets manager (Azure Key Vault, AWS Secrets Manager, HashiCorp Vault), not from disk.
- Rotate keys every 6–12 months. Publish the new selector first, switch signing, then withdraw the old DNS record after a grace period.
Verifying a Signed Message from a File
Verification is the symmetric operation: given a signed .eml, DkimVerifier extracts the DKIM-Signature header, performs a DNS lookup against <selector>._domainkey.<domain> for the public key, and recomputes the hash. The result is a DkimResult with isValid() and getErrorMessage().
DkimResult result = DkimVerifier.verify("signed-message.eml");
if (result.isValid()) {
System.out.println("[OK] DKIM signature verification successful!");
System.out.println("The message was signed by the claimed domain.");
} else {
System.out.println("[FAIL] DKIM signature verification failed!");
System.out.println("Error: " + result.getErrorMessage());
}
The verification process is:
- Extract the
DKIM-Signatureheader from the message. - Query DNS for the public key (
selector._domainkey.domain). - Verify the signature using the public key.
- Compare the computed body hash with the signed body hash.
d=example.com will always fail with a DNS-lookup error, because example.com does not publish a DKIM record. Use a domain you control (or a known-good test message) for real verification tests.
Verifying from a Stream
When the message is not on disk — it came from an IMAP fetch, a queue, an HTTP upload, or blob storage — use the stream overload:
try (InputStream stream = Files.newInputStream(Paths.get("signed-message.eml"))) {
DkimResult result = DkimVerifier.verify(stream);
if (result.isValid()) {
System.out.println("[OK] DKIM signature verified successfully from the stream!");
} else {
System.out.println("[FAIL] Verification failed!");
System.out.println("Error: " + result.getErrorMessage());
}
}
Stream-based verification is useful when:
- working with email fetched by IMAP/POP3 clients;
- processing emails from databases or cloud storage;
- building web applications that receive emails over HTTP.
verify overloads block until the DNS lookup completes, and Aspose.Email for Java offers no asynchronous counterpart of the .NET VerifyAsync method. In a request handler or a UI thread, run the verification on a worker thread — for example through an ExecutorService or CompletableFuture.supplyAsync(...).
End-to-End: Load, Sign, Save, Verify
The pieces above combine into a single workflow. This is the full sign-and-verify pipeline you would embed inside a transactional-email service:
// Step 1: Load the private key
PrivateKey privateKey = PemReader.getPrivateKey("sample-private-key.pem");
// Step 2: Create the signature information
DKIMSignatureInfo signInfo = new DKIMSignatureInfo("dkim", "example.com");
signInfo.setHashAlgorithm(DKIMHashAlgorithm.RSASha256);
signInfo.setHeaderCanonicalization(CanonicalizationType.Relaxed);
signInfo.setBodyCanonicalization(CanonicalizationType.Relaxed);
signInfo.getHeaders().addItem("From");
signInfo.getHeaders().addItem("To");
signInfo.getHeaders().addItem("Subject");
signInfo.getHeaders().addItem("Date");
signInfo.getHeaders().addItem("MIME-Version");
// Step 3: Build the message
MailMessage mailMessage = new MailMessage(
"john.doe@example.com",
"jane.smith@example.org",
"Important Document - DKIM Signed",
"Please find the attached document.\n\nBest regards,\nJohn Doe");
mailMessage.setFrom(new MailAddress("john.doe@example.com", "John Doe"));
mailMessage.getTo().addMailAddress(new MailAddress("jane.smith@example.org", "Jane Smith"));
mailMessage.setDate(new Date());
mailMessage.getHeaders().add("MIME-Version", "1.0");
// Step 4: Sign the message
MailMessage signedMessage = mailMessage.dKIMSign(privateKey, signInfo);
// Step 5: Save the signed message
signedMessage.save("end-to-end-signed.eml");
// Step 6: Verify the signature
DkimResult result = DkimVerifier.verify("end-to-end-signed.eml");
if (result.isValid()) {
System.out.println(" [OK] Signature verification successful!");
System.out.println(" [OK] The message integrity is confirmed.");
System.out.println(" [OK] The sender domain is authenticated.");
} else {
System.out.println(" [FAIL] Verification failed: " + result.getErrorMessage());
}
// Step 7: Display the DKIM-Signature header
System.out.println("DKIM-Signature header:");
System.out.println(" " + signedMessage.getHeaders().get_Item("DKIM-Signature"));
A complete DKIM-Signature header produced by this code looks like this:
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=example.com;
h=from:to:subject:date:mime-version; q=dns/txt; s=dkim; t=1780252880;
bh=e2RkwEm0k0yLcVmhi3KeXpt14Ppx3Xx49S33/+J8OGc=;
b=Zd3sfCGGD9YdOLw1o3YHLFs7DO6V9cc7anye5E3kQ/MEdkU14daTru0sXTZCtCryvJubCs...
The interesting tags:
v=1— DKIM version.a=rsa-sha256— algorithm; reflects the hash algorithm.c=relaxed/relaxed— canonicalization (header/body).d=example.com/s=dkim— domain and selector; together they form the DNS lookup name.h=from:to:subject:date:mime-version— signed headers, in order.bh=— base64 hash of the canonicalized body.b=— the actual RSA signature over the canonicalized headers.
If you change any signed header value, or modify the body, bh and b no longer match and verification fails.
Publishing the Public Key in DNS
Signing locally is only half the job. For receivers to verify, the public counterpart of your RSA key must be published as a DNS TXT record at <selector>._domainkey.<domain>:
Record: dkim._domainkey.example.com
Type: TXT
Value: v=DKIM1; k=rsa; p=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBC...
Extract the public key from your PEM with OpenSSL:
openssl rsa -in sample-private-key.pem -pubout -out sample-public-key.pem
Strip the header/footer lines and concatenate the base64 content for the p= value. Then confirm the record is live before relying on it:
dig dkim._domainkey.example.com TXT
Online tools like DKIM Validator and MXToolbox DKIM Checker will tell you whether a real message you send is verifiable end-to-end. Use them before flipping production traffic over.