Search code examples
c#asp.net-mvcmvcmailer

Send async e-mails


I am using ASP.NET MVC 3 with MVCMailer, I tried to send e-mails using SendAsync, but actually it still take longer.

So I am trying to use Task.Factory like the code bellow:

   var task1 = Task.Factory.StartNew(
            state =>
            {
                var mail = new UserMailer();
                var msg = mail.Welcome("My Name", "myemail@gmail.com");
                msg.SendAsync(); 
            });

   task1.Wait();

The problem is, MVCMailer needs HttpContext, but inside this task I got HttpContext Null.

How can I send Async e-mails?


Solution

  • A small addition to this. Here is an extension method to help some.

    using Mvc.Mailer; 
    using System.Threading.Tasks;
    public static void SendEmailAsync(this MvcMailMessage msg, HttpContext currContext)
    {
          //make this process a little cleaner
          Task.Factory.StartNew(() =>
          {
               System.Web.HttpContext.Current = currContext;
               msg.SendAsync();
           });
    }
    

    Use it like follows from your controller methods.

    Mailers.UserMailer um = new Mailers.UserMailer();
    um.SendWelcomeEmail(dataObject).SendEmailAsync(ControllerContext.HttpContext.ApplicationInstance.Context);