sandeep kumar

sandeep kumar

  • NA
  • 58
  • 12.8k

Sending Email with Excel Attachment (2 sheets)

Oct 15 2018 11:17 AM
Hello Everyone.
 
I have code which sends an email along with excel attachments. 
The code is as follows.
My question is How can I send and email excel workbook which should contain 2 different excelsheets.(One excel workbook with 2 excel sheets). Please help me.
 
{
GridView1.Visible = true;
GridView2.Visible = true;
StringWriter stw = new StringWriter();
StringWriter stw1 = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
HtmlTextWriter hw1 = new HtmlTextWriter(stw1);
GridView1.RenderControl(hw);
GridView2.RenderControl(hw1);
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
mail.To.Add(new MailAddress(TextBox1.Text));
mail.Subject = "Sales Report";
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Text.Encoding Enc1 = System.Text.Encoding.ASCII;
byte[] mBArray1 = Enc1.GetBytes(stw1.ToString());
System.IO.MemoryStream mAtt1 = new System.IO.MemoryStream(mBArray1, false);
mail.Attachments.Add(new Attachment(mAtt, "G1.xls"));
mail.Attachments.Add(new Attachment(mAtt1, "G2.xls"));
mail.Body = "please find the attachment";
SmtpClient smtp = new SmtpClient();
mail.From = new MailAddress("mailadress", "uname");
smtp.Host = "smtp-mail.outlook.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(@"mailaddress", "password");
smtp.EnableSsl = true;
smtp.Send(mail);
Label1.Text = "Email Sent";
}
 
 
Thank you,
Sandeep 
 

Answers (8)