c# - 在运行时生成 HTML 文件并作为电子邮件附件发送

标签 c# asp.net webforms email-attachments

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

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

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

最佳答案

由于您使用的是 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()< 之前将它们替换为 Labels 或 Literals/。参见 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);

关于c# - 在运行时生成 HTML 文件并作为电子邮件附件发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9176859/

相关文章:

c# - 比较和交换作为非原子操作

c# - 使用 MVVM 模式 C# 进行实时编辑

asp.net - 有没有办法确定 ASP.Net MVC Bundle 是否在之前呈现?

c# - 如何让 ASP.NET 页面知道文件何时可以从服务器下载

javascript - ASP.NET Ajax UpdateProgress 在延迟一段时间后加载

c# - 从 Silverlight 应用程序将 cookie 设置为 HttpOnly

c# - 错误 "Could not create SSL/TLS secure channel."尽管手动设置 TLS

c# - 使用javascript验证带有数字的文本框

jquery - 多次ajax调用响应缓慢

c# - ASP.NET WebForms 设计模式