postal
postal copied to clipboard
Email send fails when no HttpContext is available in ASP MVC application
Hello!
I'm using Postal in one of my personal projects and find it very useful! However recently I've encountered a minor issue which I think is a bug in current version (I've tried latest 0.9.2 release).
I want to use email views and models of ASP MVC web application in two different scenarios. First is widespread - to send email from controller action method by using Email.Send()
. Second is more tricky and it lead to the issue - to send email from background thread by using same method Email.Send()
.
Actual problem is ArgumentException
occuring in Email.Send()
and originating from System.Web.CachedPathData.GetVirtualPathData()
. Issue manifests only if web application root doesn't match the web site root, e.g. web application is located at http://mydomain.com/MyApp/, not in http://mydomain.com/.
Problem source is in method EmailViewRenderer.UrlRoot()
, where System.Web.VirtualPathUtility
can be used to generate correct application root url if HttpContext.Current
is undefined instead of simply return http://localhost.
Now I init HttpContext.Current
manually before calling Email.Send()
as a workaround.
Here is a little snippet for the workaround that I've employed, in case anyone encountering this issue needs it.
https://gist.github.com/tuespetre/f333b6bba4f9a8b496bc
I'm grabbing a base URL from Web.config, you may or may not need that, depending on whether you wanto to include full url links in your emails.
Thank you, tuespetre! In fact, workaround I mentioned in my original message looks very similar to the code snippet you provided. But I suggest Postal to handle such case out of the box.
Very much so agreed. It would also be great if there was a configurable property to set a new base URL, so we could use something besides localhost and even https.