How to Domainkeys/DKIM email signing using the C# SMTP client?

There is a fundamental problem with trying to do DKIM signatures with System.Net.Mail.MailMessage and System.Net.Mail.SmtpClient which is that in order to sign the message, you need to poke the internals of SmtpClient in order to hash the message body as one of the steps in generating the DKIM-Signature header. The problem comes in when you have alternative views or attachments because SmtpClient will generate new multipart boundaries each time it writes out the message which breaks the body hash and thus the DKIM-Signature validity.

To work around this, you can use the MimeKit and MailKit open source libraries for .NET as an alternative framework to using System.Net.Mail.

To add a DKIM signature to a message in MimeKit, you would do something like this:

MimeMessage message = MimeMessage.CreateFromMailMessage(mailMessage);
HeaderId[] headersToSign =  new HeaderId[] { HeaderId.From, HeaderId.Subject, HeaderId.Date };

string domain = "";
string selector = "brisbane";

DkimSigner signer = new DkimSigner ("C:\my-dkim-key.pem", domain, selector) 
   SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha1,
   AgentOrUserIdentifier = "",
   QueryMethod = "dns/txt",      

// Prepare the message body to be sent over a 7bit transport (such as 
// older versions of SMTP). This is VERY important because the message
// cannot be modified once we DKIM-sign our message!
// Note: If the SMTP server you will be sending the message over 
// supports the 8BITMIME extension, then you can use
// `EncodingConstraint.EightBit` instead.
message.Prepare (EncodingConstraint.SevenBit);

message.Sign (signer, headersToSign, 

To send the message using MailKit, you would do something like this:

using (var client = new MailKit.Net.Smtp.SmtpClient ()) {
    client.Connect ("", 465, true);
    client.Authenticate ("username", "password");
    client.Send (message);
    client.Disconnect (true);

Hope that helps.

see it's a DomainKeys Identified Mail (DKIM) implementation for .Net written in C# - it enables you to sign MailMessage objects.


Not only does it allow to use DKIM for signing, also you can include S/MIME certificates, PGP certificates and more. Also, its a very mature lib - the only one i've found that handles foreign languages (apart from english) correctly, since its completely and thoroughly coded with unicode in mind.

Its free and opensource.