在运行时生成 HTML 文件并作为电子邮件附件发送 [英] Generate HTML file at runtime and send as email attachment

查看:22
本文介绍了在运行时生成 HTML 文件并作为电子邮件附件发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a project requirement that we need to attach an HTML formatted log sheet to an email that gets sent to a user. I don't want the log sheet to be part of the body. I'd rather not use HTMLTextWriter or StringBuilder because the log sheet is quite complex.

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

Is there another method that I'm not mentioning or a tool that would make this easier?

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

Note: I've worked with the MailDefinition class and created a template but I haven't found a way to make this an attachment if that's even possible.

推荐答案

由于您使用的是 WebForms,我建议您使用 将您的日志表在控件中呈现为字符串,然后将其附加到 MailMessage.

Since you're using WebForms, I would recommend rendering your log sheet in a Control as a string, and then attaching that to a MailMessage.

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

The rendering part would look a bit like this:

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() 之前用标签或文字替换它们.参见 这篇博文是一个完整的例子.

If you have editable controls (TextBox, DropDownList, etc), you'll need to replace them with Labels or Literals before calling GetRenderedHtml(). See this blog post for a complete example.

这是 MSDN 附件示例:

// 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);

这篇关于在运行时生成 HTML 文件并作为电子邮件附件发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆