2

谁能告诉我为什么以下代码以原始 Html 发送电子邮件?就像您查看页面源时的电子邮件一样。

我已经削减了代码,以免包含附件和地址。

如果我使用备用视图禁用该行,则电子邮件会正确呈现,但我还想发送纯文本版本。

using (SmtpClient client = GetSmtpClient(settings)) {
    using (MailMessage message = new MailMessage()) {
        message.IsBodyHtml = true;
        message.BodyEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");
        message.To.Add(toList);
        message.Subject = subject;
        message.Body = htmlTemplate;
        message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(textTemplate, new ContentType("text/plain")));
        client.Send(message);
     }
}

编辑:消息最初是发送文本作为主体,html 作为替代视图,但我遇到了重音字符和外来字符的问题,如此处所述,想设置IsBodyHtml为 true,这迫使我将 html 设置为主视图.

4

2 回答 2

2

我也有这个问题,但这里有一个非常精简的代码版本,对我有用......

   private MailMessage CreateEmailMessage(string emailAddress) {

        MailMessage msg = new MailMessage();

        msg.From = new MailAddress(FromEmailAddress, FromName);
        msg.To.Add(new MailAddress(emailAddress));
        msg.Subject = "Msg Subject here";

        string textBody = File.ReadAllText(TextTemplateFile);


        string htmlBody = "";
        if (EmailFormat == "html") {
            htmlBody = File.ReadAllText(HtmlTemplateFile);

            foreach (Attachment inline in InlineAttachments) {
                inline.ContentDisposition.Inline = true;
                msg.Attachments.Add(inline);
            }

            AlternateView alternateHtml = AlternateView.CreateAlternateViewFromString(htmlBody,
                                                                                      new ContentType("text/html"));
            msg.AlternateViews.Add(alternateHtml);

            AlternateView alternateText = AlternateView.CreateAlternateViewFromString(textBody,
                                                                                      new ContentType("text/plain"));
            msg.AlternateViews.Add(alternateText);

        }
        else {
            msg.Body = textBody;
        }

        return msg;
    }
于 2012-11-08T11:26:00.363 回答
1

最后,我意识到传递给方法的“htmlTemplate”字符串是charset=ISO-8859-1在电子邮件的头部定义的,因此会覆盖我在代码中所做的任何更改。

我将字符集更改为UTF-8,并将我的代码恢复为:

using (SmtpClient client = GetSmtpClient(settings)) {
  using (MailMessage message = new MailMessage()) {
    message.To.Add(toList);
    message.Subject = subject;
    message.Body = textTemplate;          
    message.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(htmlTemplate, new ContentType("text/html")));
    client.Send(message);
  }
}

并且现在可以发送文本和 html 模板以及解决重音字符问题。

于 2012-11-08T14:22:24.293 回答