If you ever need to send email from a custom SharePoint application, you probably want to utilize the capabilities already provided by SharePoint. By doing this, you keep your email settings consistent and easy to manage.
Make sure your outgoing mail settings are configured.
First you will need to be sure that outgoing mail settings are configured for SharePoint. After that you can easily send email from your custom SharePoint application using SharePoint’s native mail capabilities. You can do this in Central Administration. SharePoint alerts and other email notifications also use these settings, so unless you have a fresh SharePoint installation, this is most likely already configured.
Verify that outgoing email settings are configured.
Before attempting to send an email from your application, you can easily check to be sure that the outgoing email settings are configured. If it is not configured you can handle this properly and not bother the user with a ugly error message.
if(!SPUtility.IsEmailServerSet(web)) throw new SPException("Outgoing E-Mail Settings are not configured!");
Perhaps the easiest way to send an email using SharePoint settings is by using the SPUtility.SendEmail method. Add a reference to the Microsoft.SharePoint.Utilities namespace and your ready to go. This method will return a Boolean indicating if the email was successfully sent.
If trying to use SPUtility.SendEmail from a timer job or workflow you may have issues. The reason is that the method relies on SPContext which doesn't exist in timer jobs and workflows. In this case you may want to use the System.Net.Mail option for sending email from SharePoint.
The System.Net.Mail namespace provides an easy way to send email using SMTP. Fortunately, if SharePoint Outgoing Email Settings are configured, we already know the SMTP settings, we just need to know how to get them into our code.
string replyTo = site.WebApplication.OutboundMailReplyToAddress;
string smtpAddress = site.WebApplication.OutboundMailServiceInstance.Server.Address;
MailMessage message = new MailMessage(replyTo, "email@example.com", "Subject of the email", "Body of the email");
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(smtpAddress);
In the example above, the replyto variable is set to the “Reply-to address” from the outgoing email settings. The smtpAddress is set to the “Outbound SMTP server” from the outgoing email settings.
The SmtpClient.Send method will throw an exception if there is an issue sending the email unlike SPUtility.SendEmail which returns a Boolean.
Keep in mind that the email may be sent successfully from SharePoint but there is still a chance of it getting caught up somewhere else on it’s way to the destination.
If you receive errors when sending email using these methods but everything seems to be configured correctly, check to see if your network antivirus or firewall may be blocking the application from sending the email. (I learned this from experience!)