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

本文关键字:电子邮件 运行时 HTML 文件 | 更新日期: 2023-09-27 18:22:47

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

有没有其他我没有提到的方法或工具可以让这更容易?

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

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

由于您使用的是WebForms,我建议将控件中的日志表呈现为字符串,然后将其附加到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。请参阅此博客文章以获取完整的示例。

以下是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);

您可以将Razor用于电子邮件模板。RazorEngine或MvcMailer可能会为您提供

在Web窗体应用中使用Razor视图作为电子邮件模板

Razor视图作为电子邮件模板

http://www.codeproject.com/Articles/145629/Announcing-MvcMailer-Send-Emails-Using-ASP-NET-MVC

http://kazimanzurrashid.com/posts/use-razor-for-email-template-outside-asp-dot-net-mvc