GridView to excel after create send mail c#
- by Diego Bran
I want to send a .xlsx , first I created (It has html code in it) then I used a SMTP server to send it , it does attach the file but when I tried to open it " It says that the file is corrupted etc" any help?
Here is my code
try
{
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
// Render grid view control.
gvStock.RenderControl(htw);
// Write the rendered content to a file.
string renderedGridView = sw.ToString();
File.WriteAllText(@"C:\test\ExportedFile.xls", renderedGridView);
// File.WriteAllText(@"C:\test\ExportedFile.xls", p1);
}
catch (Exception e)
{
Response.Write(e.Message);
}
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("server");
mail.From = new MailAddress("[email protected]");
mail.To.Add("[email protected]");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
Attachment data = new Attachment("C:/test/ExportedFile.xls");
mail.Attachments.Add(data);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("user", "pass");
// SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Send(mail);
}
catch( Exception e)
{
Response.Write(e.Message);
}