0
votes

I have a Web Part in SharePoint 2010 that has an Event Receiver that fires when an item is added to a list. The Event Receiver is supposed to send a mail but does not.

It works fine when I try without the Event Receiver, how can I send mail using an Event Receiver?

StringDictionary headers = new StringDictionary();
string body = "Hi!";
headers.Add("to", "[email protected]");
headers.Add("from", "[email protected]");
headers.Add("subject", "Paulo says hi");
headers.Add("content-type", "text/html");
SPUtility.SendEmail(web, headers, body)

Thank you for helping.

1
Are you getting an exception or are there are errors in the SharePoint ULS logs?Rich Bennema

1 Answers

1
votes

And event receiver runs in the context of an HTTP request. It is known that SPUtility.SendEmail has issues with this. A common practice is to set HttpContext.Current to null while sending the email:

SPWeb thisWeb = thisSite.RootWeb;
string toField = "[email protected]";
string subject = "Test Message";
string body = "Message sent from SharePoint";
HttpContext oldContext = HttpContext.Current;
HttpContext.Current = null;

bool success = SPUtility.SendEmail(thisWeb, true, true, toField, subject, body);
HttpContext.Current = oldContext;

Reference (scroll down to the comments): http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.utilities.sputility.sendemail(v=office.12).aspx