C# – Sending mail with attachments programmatically in ASP.NET

asp.netattachmentcemail

I am dynamically generating a number of different types of files based upon a GridView in ASP.NET – an Excel spreadsheet and a HTML file. I am doing so using this code (this is just for the Excel spreadsheet):

  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=InvoiceSummary" + Request.QueryString["id"] + ".xls");
  Response.Charset = "";

  Response.ContentType = "application/vnd.xls";
  System.IO.StringWriter stringWrite = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
  contents.RenderControl(htmlWrite);
  //GridView1.RenderControl(htmlWrite);
  Response.Write(stringWrite.ToString());
  Response.End();

I would like to give users the options of emailing the generated file as an attachment to either an email address they specify or one linked with their account on the database. But I don't want the user to have to save the file, then attach it in a form – I'd like to automatically attach the generated file. Is this possible, and how easy is it?

Of course, I'll be using the System.Net.Mail class to send mail…if it's possible anyway!

Best Answer

You might be able to create System.Net.Mail.Attachment from string then send out the mail as normal.

var m = new System.Net.Mail.MailMessage(from, to, subject, body);
var a = System.Net.Mail.Attachment.CreateAttachmentFromString(stringWrite.ToString(), "application/vnd.xls");
m.Attachments.Add(a);
Related Topic