step.1
DownLoad ClosedXML dll and add reference to project
step2. Download DocumentFormat.OpenXML and add reference to
project
using System.IO;
using ClosedXML.Excel;
public void send mail(){
DataTable dt = smp.GetDataTable("select l.EMPID as [EmpID],e.Emp_Name as [EmpName], l.LDate as [ApplicationDate],l.StartDate as [FromDate],l.EndDate as [ToDate] from LeaveTable");
XLWorkbook wb = new XLWorkbook();
var ws = wb.Worksheets.Add(dt, sheetName);
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
wb.SaveAs(memoryStream);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(memoryStream, sheetName + ".xlsx", "application/vnd.ms-excel");
SendEmail(To, To1, Subject, Body, attachment);
}
public static bool SendEmail(string pTo, string pTo1, string pSubject, string pBody, System.Net.Mail.Attachment attachment)
{
MailMessage myMail = new MailMessage();
ConfigurationSettings.AppSettings["emailid"].ToString();
SmtpSection settings =(SmtpSection) ConfigurationManager.GetSection("system.net/mailSettings/smtp");
var email = settings.Network.UserName;
bool ssl = Convert.ToBoolean(ConfigurationManager.AppSettings["ssl"].ToString());
myMail.From = new MailAddress(email);
myMail.To.Add(pTo);
if (pTo1 != "")
{
myMail.CC.Add(pTo1);
}
myMail.Subject = pSubject;
myMail.Body = pBody;
myMail.Priority = MailPriority.High;
myMail.Attachments.Add(attachment);
SmtpClient client = new SmtpClient();
client.EnableSsl = ssl;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.Send(myMail);
LogMessage.LogMsg = "Mailsent to:" + pTo + myMail.Body;
LogMessage.CreateLogFile();
return true;
}