I have written an program in C# which sends out emails. Now I have a requirement to sign outbound emails using Dominkeys/DKIM, but I'm not sure how to do it.
I have set up all keys, but I don't know how to get those and how to include them in the email header.
When configuring CNAME records, in order to set up DKIM and SPF, you will need to add CNAME records to your DNS settings. The DNS settings must be for the domain you are looking to authenticate. The configuration tool will generate these CNAME records, which will point to your unique DKIM keys.
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 = "example.net"; string selector = "brisbane"; DkimSigner signer = new DkimSigner ("C:\my-dkim-key.pem", domain, selector) { SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha1, AgentOrUserIdentifier = "@eng.example.com", 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, DkimCanonicalizationAlgorithm.Relaxed, DkimCanonicalizationAlgorithm.Simple);
To send the message using MailKit, you would do something like this:
using (var client = new MailKit.Net.Smtp.SmtpClient ()) { client.Connect ("smtp.gmail.com", 465, true); client.Authenticate ("username", "password"); client.Send (message); client.Disconnect (true); }
Hope that helps.
see https://github.com/dmcgiv/DKIM.Net it's a DomainKeys Identified Mail (DKIM) implementation for .Net written in C# - it enables you to sign MailMessage objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With