Sneha K

Sneha K

  • 1.1k
  • 527
  • 189.9k

Attach Gridview as excel file in email automatically in mvc?

Feb 19 2017 9:42 AM

Hi currently i have one view called Exceptions. In that i have one button(Email button) and Gridview. Now what i want is, i want to send mail by clicking that Email button. While sending email that gridview have to attach as excel file automatically in email attachment. Is it possible in mvc. If it is possible means any one give some suggesstions and some links me to do this task.

Actually i know to how to download grid view as excel file separetly and attach that excel file manually. But that is not my requiement . I want to attach grid view as excel file automatically while clicking email button.

My Model 
 
 
public class MailModel
{
public string From { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public string Password { get; set; }
}

My controller code

//gridView code
public ActionResult UserMasterDetails()
{
var userregistrationlist = db.UserMasters.ToList();
return View(userregistrationlist);
}
//Mail code
public ActionResult EmailWithAttachment()
{
return View();
}
[HttpPost]
public ActionResult MailwithAttachment(MSSCOSEC.Models.MailModel objModelMail, HttpPostedFileBase fileUploader)
{
if (ModelState.IsValid)
{
string from = objModelMail.From; //example:- [email protected]
using (MailMessage mail = new MailMessage(from, objModelMail.To))
{
mail.Subject = objModelMail.Subject;
mail.Body = objModelMail.Body;
if (fileUploader != null)
{
string fileName = Path.GetFileName(fileUploader.FileName);
mail.Attachments.Add(new Attachment(fileUploader.InputStream, fileName));
}
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential(from, "xxxxxx13332");
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
ViewBag.Message = "Sent";
return View("EmailWithAttachment", objModelMail);
}
}
else
{
return View();
}
}

The above code is manually attach the exported gridview as excel file to mail. Buti need to attach the gridview as excel file automatocally while clicking email button. I tried level best to explain the issue. Anyone understand my issue and give some solution for my problem.

Advance thanks..

 
 
 
 

Answers (2)