Generate HTML file at runtime and send as email attachment

你。 提交于 2019-12-02 11:15:50

问题


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?

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.


回答1:


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();
}

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.

Here's the 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:


You can use Razor for email templates. RazorEngine or MvcMailer might do the job for you

Use Razor views as email templates inside a Web Forms app

Razor views as email templates

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



来源:https://stackoverflow.com/questions/9176859/generate-html-file-at-runtime-and-send-as-email-attachment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!