Java
Chilkat2 Java
Verify DKIM-Signature Headers in Downloaded Email
See more DKIM / DomainKey Examples
Downloads email from an IMAP server and verifies the DKIM-Signature header(s) in each email, if present.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Dkim;
import com.chilkatsoft.chilkat2.Imap;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Imap imap = new Imap();
// Connect to an IMAP server, login, select mailbox..
// Use TLS
imap.setSsl(true);
imap.setPort(993);
try {
imap.connect("imap.example.com");
imap.login("myLogin", "myPassword");
imap.selectMailbox("Inbox");
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
Dkim dkim = new Dkim();
// Download a max of 10 emails and verify any DKIM-Signature headers
// that are present.
// Download emails by sequence numbers (not UIDs).
boolean bUid = false;
int j = 0;
int n = imap.getNumMessages();
if (n > 10) {
n = 10;
}
JsonObject json = new JsonObject();
json.setEmitCompact(false);
// To verify DKIM-Signature headers, we need the exact unmodified MIME bytes of each email.
BinData mimeData = new BinData();
int seqNum = 1;
while (seqNum <= n) {
// The FetchSingleBd method was introduced in v9.5.0.76
try {
imap.fetchSingleBd(seqNum, bUid, mimeData);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Get the number of DKIM-Signature headers.
int numDkim = dkim.numDkimSigs(mimeData);
// Verify each..
j = 0;
while (j < numDkim) {
System.out.println("------ DKIM Signature " + j);
try {
dkim.dkimVerify(j, mimeData);
System.out.println("valid.");
} catch (ChilkatException e) {
System.out.println("Not valid.");
}
// Show the additional information about the signature verification
json.load(dkim.getVerifyInfo());
System.out.println(json.emit());
// The JSON contains information such as this:
// {
// "domain": "amazonses.com",
// "selector": "7v7vs6w47njt4pimodk5mmttbegzsi6n",
// "publicKey": "MIGfMA0GCSqG...v2GvWPqGHz6uqeQIDAQAB",
// "canonicalization": "relaxed/simple",
// "algorithm": "rsa-sha256",
// "signedHeaders": "Subject:From:To:Date:Mime-Version:Content-Type:References:Message-Id:Feedback-ID",
// "verified": "yes"
// }
j = j + 1;
}
seqNum = seqNum + 1;
}
imap.disconnect();
}
}