gpt4 book ai didi

c# - SmtpClient 发送原始 Html

转载 作者:行者123 更新时间:2023-11-27 22:37:09 25 4
gpt4 key购买 nike

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

我已经缩减了代码以便不包含附件和来自地址。

如果我禁用带有备用 View 的行,电子邮件会正确呈现,但我也想发送纯文本版本。

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 作为替代 View ,但我遇到了重音字符和外来字符的问题,如 here 所述并想将 IsBodyHtml 设置为 true,这迫使我将 html 设置为主视图。

最佳答案

我也遇到过这个问题,但这里有一个非常适合我的代码的简化版本......

   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;
}

关于c# - SmtpClient 发送原始 Html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13287801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com