Search This Blog

Friday, July 22, 2016

Programmatically Send E-Mail using SPUtility.SendEmail - SharePoint


If you want to Send E-mail through SharePoint, We can use the capabilities already provided by SharePoint. (i.e) SPUtility.SendEmail. This is basically SharePoint's native functionality for email delivery.

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.
Open Central Admin --> System Settings --> Configure Outgoing Email

Before attempting to send an email from your application, you can easily check to be sure that the outgoing email settings are configured.

bool blnIsEmailServerSet = SPUtility.IsEmailServerSet(web);

If this returns false, you should not bother trying to send the email. Instead, show an error message or notify the SharePoint administrator, to check the settings of the server. If it returns true, you are good to go:

To use this method we will require namespaces:

using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;

Code:

 Below given is the code.

            using (SPSite oSite = new SPSite("Site collection URL"))  //Site collection URL
            {
                using (SPWeb oSPWeb = oSite.OpenWeb("Subsite URL"))  //Subsite URL
                {
                    StringDictionary headers = new StringDictionary();

                    headers.Add("from", "senderEmail@domain.com");
                    headers.Add("to", "receiverEmail@domain.com");
                    headers..add("bcc","HiddenuserEmail@domain.com");
                    headers.Add("subject", "Send Email using SP Utility");
                    headers.Add("fAppendHtmlTag","True"); //To enable HTML format

                    System.Text.StringBuilder strMessage = new System.Text.StringBuilder();
                    strMessage.Append("body of the message that can include html tags also");
                 
                    strMessage.Append("<span style='color:red;'> HTML </span>");
                    SPUtility.SendEmail(oWeb, headers, strMessage.ToString());

                }
            }


Some Limitations for this method are :

1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.

To overcome the limitations, use the System.Net.Mail class methods to send E-mail.
I have given details here.

Happy Coding :)

No comments:

Post a Comment