3

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?

  • Where is your asmx hosted? Have you tried using elevated privs? – Mike Nov 6 '13 at 22:33
3

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;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.