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!
For sending mail from ASP.NET MVC we use the "System. Net.Mail" namespace.
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);
protected void btnSend_OnClick(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
byte[] data = new byte[1024];
MemoryStream stream = new MemoryStream(data);
Attachment attach = new Attachment(stream, "Attachment file name");
mail.Attachments.Add(attach);
new SmtpClient().Send(mail);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With