Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending mail with attachments programmatically in ASP.NET

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!

like image 455
Chris Avatar asked Nov 29 '10 20:11

Chris


People also ask

Which namespace using can send email in ASP NET MVC?

For sending mail from ASP.NET MVC we use the "System. Net.Mail" namespace.


2 Answers

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);
like image 69
tonyjy Avatar answered Oct 25 '22 01:10

tonyjy


    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);
    }
like image 36
Sid C Avatar answered Oct 25 '22 02:10

Sid C