Search code examples
vb.netsmtpdkimmimekit

DKIM Signing an email with MimeKit in vb.net


I am trying to get my website to send emails that are dkim signed. I found mimekit and have tried to implement the logic. I used several dkim checkers (dkim key checker and mail tester) to verify my dns record and it passes fine, but dkim validators and google and outlook show in the headers or page that the dkim fails in the email. The dkim validator above says:

Validating Signature

result = invalid

Details: bad identity

The subroutine I am using:

Private Shared Sub DKIMSignAndSend(mailMessage As System.Net.Mail.MailMessage)
   Dim message As MimeMessage = MimeMessage.CreateFromMailMessage(mailMessage)
   Dim headersToSign() As HeaderId = New HeaderId() {HeaderId.From, HeaderId.Subject, HeaderId.Date}
   Dim domain As String = "domain.com"
   Dim selector As String = "1559659173.domain"
   Dim signer As DkimSigner = New DkimSigner(String.Format("{0}\Administration\dkim.pem", System.Web.Configuration.WebConfigurationManager.AppSettings("WebsiteDirectory")), domain, selector)
   signer.SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha1
   signer.AgentOrUserIdentifier = "domain.com"
   signer.QueryMethod = "dns/txt"
   message.Prepare(EncodingConstraint.SevenBit)
   message.Sign(signer, headersToSign, DkimCanonicalizationAlgorithm.Relaxed, DkimCanonicalizationAlgorithm.Simple)

   Using client As New MailKit.Net.Smtp.SmtpClient()
      With CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
         client.Connect(.Network.Host, .Network.Port, .Network.EnableSsl)
         client.Authenticate(.Network.UserName, .Network.Password)
      End With
      client.Send(message)
      client.Disconnect(True)
   End Using
End Sub

I pass in a System.Net.Mail.MailMessage that has html and text alternate views and attachments.

Can anyone help with what I am doing wrong?


Solution

  • Sounds like your Selector or AgentOrUserIdentifier are wrong.

    Try signer.AgentOrUserIdentifier = "@domain.com"