i have developed a mvc web app in asp.net i have created a quartz.net job to send an email daily in background and it all works great but i have a problem with the attachment, in another class i create an excel attachment and if i try to call that method in my job it give me error in that method that create the excel, i receive this error message in the HttpContext.Current code "System.NullReferenceException: 'Object reference not set to an instance of an object.'"
This is my creation Excel code:
public static class CreazioneExl
{
public static void CreazioneFile(ExcelPackage ex, string title)
{
using (var memoryStream = new MemoryStream())
{
HttpContext cur = HttpContext.Current;
cur.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
cur.Response.AddHeader("content-disposition", "attachment ; filename=" + title + ".xlsx");
ex.SaveAs(memoryStream);
memoryStream.WriteTo(cur.Response.OutputStream);
cur.Response.Flush();
cur.Response.End();
}
}
}
This is my SendMailJob
public void SendMail()
{
ExcelPackage ex = ReportMethods.ExportExcelTotal(model);
CreazioneExl.CreazioneFile(ex, "EmailXml");
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress("mymail@hotmail.com", "Me");
Msg.To.Add(new MailAddress("clientmail@gmail.com", "Client"));
Msg.Subject = "Mail notifiche TrelloReporterApp ";
Msg.Body = "Mail automatica di notifiche giornaliera";
Msg.IsBodyHtml = true;
var filePath = @"C:\Users\me\Downloads\EmailXml.xlsx";
Msg.Attachments.Add(new System.Net.Mail.Attachment(filePath));
SmtpClient Smtp = new SmtpClient("smtp.live.com", 25);
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
Smtp.UseDefaultCredentials = false;
NetworkCredential Credential = new NetworkCredential("mymail@hotmail.com", "mypassword");
Smtp.Credentials = Credential;
Smtp.EnableSsl = true;
Smtp.Send(Msg);
File.Delete(@"C:\Users\me\Downloads\EmailXml.xlsx");
}
}
And i wanted to start the mail job at the start of the application in the Global.asax:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//other things
//send email in background at the start of the application
JobScheduler.Start();
}
}
The creation of the excel works well when i use it in another context (print that excel that i create clicking a button) but when i use it in this background job i have that error that all the Http.Context is null... Can someone help me?