Sending mail with attachments programmatically in ASP.NET

后端 未结 4 1794
轮回少年
轮回少年 2021-02-03 13:13

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

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-03 13:52

    Here is an working example of what I mentioned earlier, there is a little extra logic in the code to parse the GridView to a Table.

            //Table to store our GridView Data
            Table table = new Table();
    
            //Parse our GridView into Table, stored in a StringBuilder
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  header
                    if (GridView1.HeaderRow != null)
                    {
                        table.Rows.Add(GridView1.HeaderRow);
                    }
    
                    //  details
                    foreach (GridViewRow row in GridView1.Rows)
                    {
                        table.Rows.Add(row);
                    }
    
                    //  footer
                    if (GridView1.FooterRow != null)
                    {
                        table.Rows.Add(GridView1.FooterRow);
                    }
    
                    //  render table
                    table.RenderControl(htw);
                }
            }
    
    
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (StreamWriter writer = new StreamWriter(memoryStream))
                {
                    //Convert StringBuilder to MemoryStream
                    writer.Write(sb.ToString());
                    writer.Flush();
    
                    //Create Message
                    MailMessage message = new MailMessage();
                    message.To.Add(new MailAddress("you@address.com", "You"));
                    message.From = new MailAddress("me@address.com", "Me");
                    message.Subject = "The Subject";
    
                    //Create Attachment
                    Attachment attachment = new Attachment(memoryStream, "InvoiceSummary.xls", "application/vnd.xls");
    
                    //Attach Attachment to Email
                    message.Attachments.Add(attachment);
    
                    //Open SMTP connection to server and send
                    SmtpClient smtp = new SmtpClient();
                    smtp.Port = 25;
                    smtp.Send(message);
                }
            }
    

提交回复
热议问题