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.
For sending mail from ASP.NET MVC we use the "System. Net.Mail" namespace.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With