需要帮助使用html正文实现DKIM-Signature

时间:2012-04-27 13:53:23

标签: c# email bouncycastle domainkeys

我正在使用此代码签署( DKIM-Signature )我的电子邮件,它的工作非常适合纯文本,但我无法发送html正文电子邮件。

 string smtp = "mail.***";
            string from = "***";
            string subject = "***";



            string to = "check-auth@verifier.port25.com";

            string body = "i am body of email<b>Bold text</b>";
            string base64privatekey = @"-----BEGIN RSA PRIVATE KEY-----***-----END RSA PRIVATE KEY-----";

            HashAlgorithm hash = new SHA256Managed();

            string hashBody = body.Replace(Environment.NewLine, "=0D=0A") + Environment.NewLine;
            byte[] bodyBytes = Encoding.ASCII.GetBytes(hashBody);
            string hashout = Convert.ToBase64String(hash.ComputeHash(bodyBytes));

            TimeSpan t = DateTime.Now.ToUniversalTime() - DateTime.SpecifyKind(DateTime.Parse("00:00:00 January 1, 1970"), DateTimeKind.Utc);

            string signatureHeader = "v=1; " +
             "a=rsa-sha256; " +
             "c=relaxed/relaxed; " +
             "d=***; " +
             "s=p; " +
             "t=" + Convert.ToInt64(t.TotalSeconds) + "; " +
             "bh=" + hashout + "; " +
             "h=From:To:Subject:Content-Type:Content-Transfer-Encoding; " +
             "b=";

            string canonicalizedHeaders =
            "from:" + from + Environment.NewLine +
            "to:" + to + Environment.NewLine +
            "subject:" + subject + Environment.NewLine +
            @"content-type:text/plain; charset=us-ascii
content-transfer-encoding:quoted-printable
dkim-signature:" + signatureHeader;

            TextReader reader = new StringReader(base64privatekey);
            Org.BouncyCastle.OpenSsl.PemReader r = new Org.BouncyCastle.OpenSsl.PemReader(reader);
            AsymmetricCipherKeyPair o = r.ReadObject() as AsymmetricCipherKeyPair;
            byte[] plaintext = Encoding.ASCII.GetBytes(canonicalizedHeaders);
            ISigner sig = SignerUtilities.GetSigner("SHA256WithRSAEncryption");
            sig.Init(true, o.Private);
            sig.BlockUpdate(plaintext, 0, plaintext.Length);
            byte[] signature = sig.GenerateSignature();
            signatureHeader += Convert.ToBase64String(signature);

            MailMessage message = new MailMessage();
            message.From = new MailAddress(from);
            message.To.Add(new MailAddress(to));

            message.Subject = subject;
            message.Body = body;

            message.Headers.Add("DKIM-Signature", signatureHeader);
            System.Net.NetworkCredential _Credential = new System.Net.NetworkCredential("***", "***");
            SmtpClient client = new SmtpClient(smtp);
            client.Port = 26;
            client.Credentials = _Credential;
            client.Send(message);
            Console.Write("sent to: " + to);

0 个答案:

没有答案