Question

I have a function inside an asmx page which needs to send an email, but SPUtility.SendEmail returns false. SPContext.Current is null, so I create an SPSite object with the site url, and from that, I get the rootWeb, which is what I pass to SPUtility.SendEmail. If I call this exact code (it's encapsulated in a helper function) as the result of a postback, using SPContext.Current.Web, it works. Examining the SPWeb object from both calls, they look identical.

if (string.IsNullOrEmpty(siteUrl))
    success = SPUtility.SendEmail(SPContext.Current.Web, headers, message);
else
{
    using (SPSite site = new SPSite(siteUrl))
    {
        success = SPUtility.SendEmail(site.RootWeb, headers, message);
    }
}

Any ideas how to send the email?

Was it helpful?

Solution

This is not an ideal solution, however if your code works when there is an SPContext, you can create a fake SPContext when it does not exist:

using (var site = new SPSite("url"))
{
    using (var web = site.OpenWeb())
    {
        HttpContext newContext = null;
        if (HttpContext.Current == null)
        {
            var request = new HttpRequest("", web.Url, "");
            newContext = new HttpContext(request, new HttpResponse(TextWriter.Null));
            HttpContext.Current = newContext;
        }
        HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
        HttpContext.Current.Items["HttpHandlerSPSite"] = site;

        // Do your code here

        if (newContent != null)
            HttpContext.Current = null;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top