Obscure SPUtility.SendMail Behavior When Manually Passing in Mail Headers

Posted by Damon on Simple Talk See other posts from Simple Talk or by Damon
Published on Mon, 17 Jan 2011 18:01:43 GMT Indexed on 2011/01/18 1:56 UTC
Read the original article Hit count: 258

Filed under:

There are two ways to send mail in SharePoint: you can either use the mail components from the System.Net namespace, or you can send email using SharePoint's SPUtility.SendMail method.  One of the benefits of the SPUtility.SendMail method is that it uses the mail configuration from SharePoint, so you can manage settings in Central Administration instead of having to go through and modify your web.config file. 

SPUtility.SendMail can get the job done, but it's defiantly not as developer friendly as the components from the System.Net namespace.  If you want to CC someone on an email, for example, you do NOT have a nice CC parameter - you have to manually add the CC mail header and pass it into the SPUtility.SendMail method.  I had to do this the other day, and ran into a really obscure issue.

If you do NOT pass the headers into the method then SharePoint sends the email using the From Address configured in the Outgoing Mail settings in Central Admin. 

If you pass headers into the method, but do not include the from header, then SharePoint sends the mail using the email address of the current user.

This can be an issue if your mail server is setup to reject an email from an invalid email address or an email address that is not on your domain.  The way to fix this issue is to always pass in the from header.  If you want to use the configured From address, then you can do the following:

SPWebApplication webApp = SPWebApplication.Lookup(new Uri(SPContext.Current.Site.Url));
StringDictionary headers = new StringDictionary();
headers.Add("from", webApp.OutboundMailSenderAddress);

© Simple Talk or respective owner