Generate HTML file at runtime and send as email attachment

I have a project requirement that we need to attach an HTML sheet of the journal to the email that is sent to the user. I do not want the log list to be part of the body. I would prefer not to use HTMLTextWriter or StringBuilder, because the log list is pretty complicated.

Is there another method that I don't mention, or a tool that will simplify this?

Note. I worked with the MailDefinition class and created a template, but I did not find a way to make this attachment, if possible.

+1
c # webforms email-attachments
07 Feb 2018-12-12T00:
source share
2 answers

Since you are using WebForms, I would recommend rendering your log in the control as a string , and then attach this to MailMessage .

Part of the rendering would look something 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 need to replace them with labels or literals before calling GetRenderedHtml() . See this blog post for a complete example.

Here is an example MSDN 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); 
+3
Feb 07 2018-12-12T00:
source share

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

Use Razor views as message templates in a web form application

Razor treats as letter 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

+2
Feb 07 2018-12-12T00:
source share



All Articles