Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any MVC Email Packages That Don't Require a HTTP Context?

We send emails from our ASP.NET MVC 3 Razor Web Application.

Currently we're using ActionMailer.NET.

I've looked at MvcMailer.

The problem with both is that they need a Http Context to execute.

The problem with this is that i want to send emails asychronously. Now i know you can asynchronously do the actual send (e.g the SMTP call), but i want the entire process of sending an email to be asynchronous, e.g:

public ActionResult DoSomething(Something something)
{
   _db.Save(something);

   Task.Factory.StartNew(() => {
      new MailController().DoSomething().Send(something);
   });

   return RedirectToAction("Index");
}

In the "DoSomething" method, i query the database again, do other stuff, etc....i want all this to be asynchronous - hence the entire call is wrapped in a task, a opposed to just doing .SendAsync(). Hope that makes sense.

The above example is ActionMailer, and it breaks - because the HTTP context is gone in the spawned thread.

Does anyone know how i can get this to work, or alternatively another package which does not rely on the existence of a HTTP context?

I'm not sure why a HTTP context is required - there is no request routing here, simply parsing a view which is on the file system into HTML.

like image 454
RPM1984 Avatar asked May 30 '12 07:05

RPM1984


People also ask

Which namespace using can send email in ASP NET MVC?

For sending mail from ASP.NET MVC we use the "System. Net.Mail" namespace.

What is HttpContext MVC?

ASP.NET MVC 5 for Beginners The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.


1 Answers

You may checkout postal which uses the RazorViewEngine:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        Task.Factory.StartNew(() =>
        {
            Thread.Sleep(5000);
            dynamic email = new Email("Example");
            email.To = "[email protected]";
            email.FunnyLink = "some funny link";
            email.Send();
        });

        return View();
    }
}

and inside ~/Views/Emails/Example.cshtml:

To: @ViewBag.To
From: [email protected]
Subject: Important Message

Hello,
You wanted important web links right?
Check out this: @ViewBag.FunnyLink

Also make sure you have read and understood the dangers of implementing background tasks in ASP.NET applications before putting your application on production.

like image 144
Darin Dimitrov Avatar answered Sep 28 '22 00:09

Darin Dimitrov