Thursday, 16 November 2017

Setting up DomainKeys Identified Mail (DKIM) email authentication with .Net in 5 minutes

DomainKeys Identified Mail (DKIM) allows e-mail senders to couple their domain name with an e-mail message, thus vouching for its authenticity.

This is achieved by adding a digital signature to the e-mail message header.

Heres how you can do it in .Net.
  1. Add the DKIM.net nuget package to your solution.
     
  2. Create RSA a key pair at http://travistidwell.com/jsencrypt/demo/
     
  3. Add a TXT DNS record for your domain with
    name/host:   default._domainkey
    value:           k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBg QCHhsB36ViuKvPHAgrbVC9MPr9DuquOIseApXB4kLVy/1Hw72Moeqsmyfl M9oXL81bXVpFIU/pBc3GJUL/Fp7Pgp5VTzheelQRfqlFqKL+bt6bTXA1gz1q IAICEctjbnLxzHGbnKiotVXycfckAki01WboyZbdr5wZ 1j6Otco7x9wIDAQAB
    (without newlines copied from step 2)
     
  4. Add a TXT DNS record for your domain with
    name/host:  _domainkey
    value:         o=~;r=mail@yourdomain.com
      
  5. In code: 

   var email = new MailMessage("mail@yourdomain.com",recipient);
   email.Subject = message.Subject;

   email.Body = message.Body;

   email.IsBodyHtml = true;

   var mailClient = new SmtpClient(strSmtpServer, smtpServerPort) {

      Credentials = new NetworkCredential(strSmtpServerLogin, strSmtpServerPwd)
   };
   var privateKey = PrivateKeySigner.Create(@"-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCHhsB36ViuKvPHAgrbVC9MPr9DuquOIseApXB4kLVy/1Hw72Mo
eqsmyflM9oXL81bXVpFIU/pBc3GJUL/Fp7Pgp5VTzheelQRfqlFqKL+bt6bTXA1g
z1qIAICEctjbnLxzHGbnKiotVXycfckAki01WboyZbdr5wZ1j6Otco7x9wIDAQAB
AoGAdj6f1v+FHBDluRCTIGIHEmL8xb8sx0qY/ilaRBcd+UPC3pA+16aPhbxbA0dj
3VpmvmMNRyneAxUSTlhhubZkPacgX4h7p3B7ZOmFnzlbyENXsWcUJHGRTgt6c+0s
PRfnCr0OH0TnSWunY8pQ3AKksXdvRD1Zm3lLytN0IpH2wgECQQDiyRmEHZbbBdBJ
14YCkH2imGF/NFXazhLFBpgO0zzp3yMluQ+/cTeEZMWEFYSk1H5zwPBKkd3SD7e7
H3zXa+03AkEAmPwe4qYqahet43t7UXSBUP7zYaY4k/8y0xqnUeFKp3TOJTyowIcl
jBtDQnW5xFVPtbUVIqjx6HJqhhmuBtmBQQJABMPW7mi0v7taigKmRS2GBkGPYt3V
o/hKeqtNzJnxoLRYh7VguFQHp5d6cvEEzXXNhl8abWatM3mzEZJyzA/vdwJBAJaO
CBclUDh4dTiaHRJchacgQISpAKUlUO9QG7oI7V8/JGChAbH3ToxDiD2vfdIp4vf/
7XzeprMLZqnyO8Gh7AECQQC5U/I+yCqZtcyFTuwJYTd+dROtR7mlEZDtR+W10ZsO
luKz+8ZsoWLH4XdUWX0LRoam4dZ9PfM8uHGHBhpIY7rG
-----END RSA PRIVATE KEY-----"); //with newlines and the RSA PRIVATE KEY header/footer

   var domainKeySigner = new DomainKeySigner(privateKey, "yourdomain.com", "default",
       new string[] { "From", "To", "Subject" });
   email.DomainKeySign(domainKeySigner);

   var dkimSigner = new DkimSigner(privateKey, "yourdomain.com", "default",
         new string[] { "From", "To", "Subject" });
   email.DkimSign(dkimSigner);              

   mailClient.SendMailAsync(email);


and that is it. Now start sending your emails. If you test sending to gmail hopefully you will no longer see the red questionmark to the left of the senders address.











This DKIM solution is implemented on gooddocus.com