【问题标题】:Generate HTML file at runtime and send as email attachment在运行时生成 HTML 文件并作为电子邮件附件发送
【发布时间】:2012-02-07 13:12:38
【问题描述】:

我有一个项目要求,我们需要将 HTML 格式的日志表附加到发送给用户的电子邮件中。 我不希望日志表成为正文的一部分。我宁愿不使用 HTMLTextWriter 或 StringBuilder,因为日志表非常复杂。

有没有我没有提到的另一种方法或可以使这更容易的工具?

注意:我已经使用 MailDefinition 类并创建了一个模板,但如果可能的话,我还没有找到将其作为附件的方法。

【问题讨论】:

    标签: c# asp.net webforms email-attachments


    【解决方案1】:

    由于您使用的是 WebForms,我会推荐 rendering your log sheet in a Control as a string,然后是 attaching that to a MailMessage

    渲染部分看起来有点像这样:

    public static string GetRenderedHtml(this Control control)
    {
        StringBuilder sbHtml = new StringBuilder();
        using (StringWriter stringWriter = new StringWriter(sbHtml))
        using (HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter))
        {
            control.RenderControl(textWriter);
        }
        return sbHtml.ToString();
    }
    

    如果您有可编辑的控件(TextBoxDropDownList 等),则需要在调用 GetRenderedHtml() 之前将它们替换为标签或文字。有关完整示例,请参阅 this blog post

    这是MSDN example for attachments

    // Specify the file to be attached and sent.
    // This example assumes that a file named Data.xls exists in the
    // current working directory.
    string file = "data.xls";
    // Create a message and set up the recipients.
    MailMessage message = new MailMessage(
       "jane@contoso.com",
       "ben@contoso.com",
       "Quarterly data report.",
       "See the attached spreadsheet.");
    
    // Create  the file attachment for this e-mail message.
    Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
    // Add time stamp information for the file.
    ContentDisposition disposition = data.ContentDisposition;
    disposition.CreationDate = System.IO.File.GetCreationTime(file);
    disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
    disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
    // Add the file attachment to this e-mail message.
    message.Attachments.Add(data);
    

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 我目前没有使用 MVC,所以我不认为这是一个选项。
      • 好的,很高兴知道,但不幸的是,我仍在运行 asp.net 3.5,看来 RazorEngine 需要 4.0
      猜你喜欢
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      相关资源
      最近更新 更多