0

我在使用 SMTP/.NET 邮件将内联 HTML 发送到电子邮件时遇到问题。我已经尝试过标准类以及 MailDefininition 类,但我不断地内联原始代码,而不是翻译的页面。

我知道这可能是我缺少的一些小东西,下面是我的代码。谢谢

     public static void SendMail(string toAddress,  string subject, string messageBody)
    {
        MailDefinition message = new MailDefinition();
        message.CC = MailCCAddress;
        message.From = "orders@test.com";
        message.Subject = subject;
        message.IsBodyHtml = true;
        ListDictionary replacements = new ListDictionary();

        System.Net.Mail.MailMessage fileMsg;
        fileMsg = message.CreateMailMessage(toAddress, replacements, messageBody, new System.Web.UI.Control());

        string _hostName = HostName;

        SmtpClient client = new SmtpClient(_hostName);
        client.Credentials = CredentialCache.DefaultNetworkCredentials;
        //client.Send(message);
        client.Send(fileMsg);
    }
4

2 回答 2

2

MailMessage如果您仍然遇到问题,您可能还希望设置Body-Encoding。例如,

//Nick's code
MailMessage mail = new MailMessage("orders@test.com", toAddress, subject, messageBody);
mail.IsBodyHtml = true;

//set encoding
mail.BodyEncoding = Encoding.UTF8; //or SevenBit, etc, whatever is appropriate.

//send
SmtpClient client = new SmtpClient(_hostName);
client.Send(mail);

您还可以使用 AlternateViews 集合,它可以让您更好地控制内容的 MIME 类型(因此您可以将其指定为 text/html 等)。您还可以使用它来选择性地包含文本版本和 HTML 版本,如下所示:

//create the mail message
MailMessage mail = new MailMessage("orders@test.com", toAddress) { Subject = subject };

//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");
//then we create the Html part
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");

//add both views
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);

//send the message as before
于 2012-12-27T19:17:17.487 回答
0
MailMessage mail = new MailMessage("orders@test.com", toAddress, 
    subject, messageBody);

mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient(_hostName);
client.Send(mail);

如果这不起作用,则可能是您的 messageBody 有问题。您可以尝试调试代码,看看 messageBody 不是正确的 html 是否存在问题,或者它可能有一些字符被转义。

于 2012-12-27T17:49:02.600 回答