This project is read-only.

CSC510252. Send an e-mail from a WCF service when SPContext is not available.


Sending an e-mail from a WCF service when SPContext is not available could fail. As a workaround, you have to prevent the mail function from reading the current context by using HttpContext.Current = null. If it can’t, it will retrieve the right context and it will then work.


    using (SPSite site = new SPSite("http://sharepointserve"))
        SPWeb thisWeb = site.RootWeb;
            string to = "";
            string subject = "Test Message";
            string body = "A message from SharePoint";
            HttpContext curCtx = HttpContext.Current; 
            HttpContext.Current = null;
            bool success = SPUtility.SendEmail(thisWeb, true, true, to, subject, body); 
            HttpContext.Current = curCtx;
catch (Exception ex)
    // Exception handling skipped for clarity 

The current context is set to null to force the context to be retrieved again. Saving the current context ensures that the service works properly after the method has been executed.

Note: ASMX Web Services require the same procedure.


When Hosting Custom WCF Services in SharePoint, SPContext is Null due to MultipleBaseAddressBasicHttpBindingServiceHostFactory Bug
SPUtility.SendEmail method

Last edited Aug 1, 2014 at 2:39 PM by dvd73, version 1


No comments yet.