【问题标题】:Send an email with a HTML file as body (C#)发送带有 HTML 文件作为正文的电子邮件 (C#)
【发布时间】:2018-11-21 12:06:42
【问题描述】:

如何使用 HTML 文件设置 MailMessage 的正文?

【问题讨论】:

标签: c# asp.net


【解决方案1】:

如果你使用System.Net.Mail.MailMessage,你可以使用:

mail.IsBodyHtml = true;

System.Web.Mail.MailMessage 已过时,但如果使用它:mail.BodyFormat 有效。

【讨论】:

    【解决方案2】:

    只需将MailMessage.BodyFormat属性设置为MailFormat.Html,然后将html文件的内容转储到MailMessage.Body属性即可:

    using (StreamReader reader = File.OpenText(htmlFilePath)) // Path to your 
    {                                                         // HTML file
        MailMessage myMail = new MailMessage();
        myMail.From = "from@microsoft.com";
        myMail.To = "to@microsoft.com";
        myMail.Subject = "HTML Message";
        myMail.BodyFormat = MailFormat.Html;
    
        myMail.Body = reader.ReadToEnd();  // Load the content from your file...
        //...
    }
    

    【讨论】:

    • 所以,只是为了说明,这个答案对应于System.Web.Mail.MailMessage。在尝试设置 BodyFormat 时,我遇到了问题,因为 Reflector 告诉我它不存在。原因是,我使用的是System.Net.Mail.MailMessage(在那个类中,有一个名为IsBodyHtmlbool 标志,您可以设置它)。此外,如果所有条件相同,建议使用System.Net.Mailstackoverflow.com/q/64599/324527
    • 现在已经改变了。您应该使用“myMail.IsBodyHtml = true;”
    • 如果我想改变HTML代码的内容怎么办?例如:Dear *value_from_C#_variable*
    猜你喜欢
    • 2018-05-12
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    • 2018-11-07
    • 1970-01-01
    • 2021-06-12
    相关资源
    最近更新 更多