How To Send Email with SPUtility in Sharepoint

There is no doubt that email is a key functionality in today's enterprise. In organizations where SharePoint 2007 has also become a key collaboration platform you'll increasingly find situations where you need to send email from within the SharePoint environment. This article shows how to accomplish that, using the SPUtility class's SendEmail method.

There are many scenarios where you might want to send an email notification.

In this scenario, whenever a document gets uploaded to the document library, the system first applies some business rules and logic, and then notifies users interested in that document by email. Although this is a simple scenario, it shows clearly how email is an important component of today's organizational strategies. As a SharePoint developer, that means you need a quick and easy way to send email.

Traditionally developers have used the SMTP class in ASP.NET to send email; it's quite powerful and provides fine granular control over the contents. But to use it, you need to add appropriate references and set the various properties. When your requirements are simple—such as simply sending some brief text notifications, or when email is only part of some other automated process or workflow, you may want to look at the SPUtility class's SendEmail method instead. While it doesn't have the power of ASP.NET's SmtpClient class, it's much easier to use. The following example sends email using SPUtililty.SendEmail:

private Boolean SendEmail() {   try   {     bool flag = false;     SPSecurity.RunWithElevatedPrivileges(       delegate()     {       using (SPSite site = new SPSite(         SPContext.Current.Site.ID,         SPContext.Current.Site.Zone))       {         using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))         {           flag = SPUtility.SendEmail(web, true, true,                                       "TO@example.com",                                      "Subject",                                      "This is a sample email Body");         }       }     });     return flag;   }   catch (System.Exception exp)   {     // Do some error logging     return false;   } }  

The first thing to remember is that you need to use the Microsoft.SharePoint.Utilities namespace, which contains the SPUtility class that exposes the SendEmail method. Note that SendEmail occupies only one line in the preceding code. You should also note that you may need to elevate privileges, because the current user context may not have sufficient permission to send email.

There are several overloads of the SendEmail method. The parameters for the version shown are an SPWeb object (web), followed by two Boolean parameters: AppendHtmlTags, which when true appends an HTML tag to the message, false otherwise, and HtmlEncode, which when true encodes the message and replace characters in HTML tags with entities. The last three parameters are strings that correspond to the email's To, Subject, and Body fields, respectively.

The SendEmail method returns a Boolean true for success or false if the send attempt failed.

As you can see, sending basic email using SendEMail is straightforward; however, note these key considerations:

  • Attachments are not allowed.
  • By default, the message body cannot exceed 2048 characters. SendEMail will truncate all characters beyond 2048. The workaround is to ensure that no single line in your message body exceeds 2048 characters. Simply add newline characters as needed to keep the lines under the 2048 character limit.
  • By default, the From address is always set to the value from the Central Administration Outbound Mail Sender Address field.


How To Send Email with SPUtility in Sharepoint

There is no doubt that email is a key functionality in today's enterprise. In organizations where SharePoint 2007 has also become a key collaboration platform you'll increasingly find situations where you need to send email from within the SharePoint environment. This article shows how to accomplish that, using the SPUtility class's SendEmail method.

There are many scenarios where you might want to send an email notification.

In this scenario, whenever a document gets uploaded to the document library, the system first applies some business rules and logic, and then notifies users interested in that document by email. Although this is a simple scenario, it shows clearly how email is an important component of today's organizational strategies. As a SharePoint developer, that means you need a quick and easy way to send email.

Traditionally developers have used the SMTP class in ASP.NET to send email; it's quite powerful and provides fine granular control over the contents. But to use it, you need to add appropriate references and set the various properties. When your requirements are simple—such as simply sending some brief text notifications, or when email is only part of some other automated process or workflow, you may want to look at the SPUtility class's SendEmail method instead. While it doesn't have the power of ASP.NET's SmtpClient class, it's much easier to use. The following example sends email using SPUtililty.SendEmail:

private Boolean SendEmail() {   try   {     bool flag = false;     SPSecurity.RunWithElevatedPrivileges(       delegate()     {       using (SPSite site = new SPSite(         SPContext.Current.Site.ID,         SPContext.Current.Site.Zone))       {         using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))         {           flag = SPUtility.SendEmail(web, true, true,                                       "TO@example.com",                                      "Subject",                                      "This is a sample email Body");         }       }     });     return flag;   }   catch (System.Exception exp)   {     // Do some error logging     return false;   } }  

The first thing to remember is that you need to use the Microsoft.SharePoint.Utilities namespace, which contains the SPUtility class that exposes the SendEmail method. Note that SendEmail occupies only one line in the preceding code. You should also note that you may need to elevate privileges, because the current user context may not have sufficient permission to send email.

There are several overloads of the SendEmail method. The parameters for the version shown are an SPWeb object (web), followed by two Boolean parameters: AppendHtmlTags, which when true appends an HTML tag to the message, false otherwise, and HtmlEncode, which when true encodes the message and replace characters in HTML tags with entities. The last three parameters are strings that correspond to the email's To, Subject, and Body fields, respectively.

The SendEmail method returns a Boolean true for success or false if the send attempt failed.

As you can see, sending basic email using SendEMail is straightforward; however, note these key considerations:

  • Attachments are not allowed.
  • By default, the message body cannot exceed 2048 characters. SendEMail will truncate all characters beyond 2048. The workaround is to ensure that no single line in your message body exceeds 2048 characters. Simply add newline characters as needed to keep the lines under the 2048 character limit.
  • By default, the From address is always set to the value from the Central Administration Outbound Mail Sender Address field.


Userful 7 Projects for SharePoint 2010 on CodePlex

Popular software products usually benefit from strong technical communities. That is certainly the case with SharePoint. SharePoint 2007 saw a rise in the number of open source projects on sites such as CodePlex to fill in the gaps of what is not offered out of the box. With SharePoint 2010, many more features were included in the base product and the development tools such as Visual Studio, but there are still some very useful tools on CodePlex to help you get more out of SharePoint 2010.

Some of the SharePoint 2010 projects on CodePlex are geared toward farm administrators, site collection administrators, and power users, but the majority of the projects seem to be focused on developers. I will present projects for all four audiences and identify for whom it was intended.

SharePoint Manager 2010

SharePoint Manager 2010 is useful for both SharePoint farm administrators and developers alike. If you are a farm administrator, the tool will allow you to browse the configuration properties of your SharePoint servers and sites. In many cases, you can change the properties right from within the application. For developers, this tool helps you become more familiar with the objects in a SharePoint farm so that you will know what is available to set programmatically.

SPServices jQuery Library for SharePoint

The SPServices jQuery Library for SharePoint is a real gem. This project is ideal for SharePoint power users or traditional web developers who do not have deep SharePoint development experience using Visual Studio. The idea of the project is to wrap calls to the SharePoint web services so that they are easily called by someone who is familiar with jQuery (a JavaScript framework). The library includes features and behaviors that are not available out of the box in SharePoint. For example, if you want to filter a drop down list based on the criteria that was entered in another drop down list, this tool will allow you to do so through some easy to follow JavaScript code.

SharePoint Content Deployment Wizard

The SharePoint Content Deployment Wizard has proven to be useful time and time again. From migrating content during server upgrades, to refreshing content from your production to your development farm, this tool is a time saver. You can export SharePoint content at the site collection level, site, list or even individual list items, and then import them on a target server or site.

SharePoint 2010 Bulk Document Importer

If you need to import documents from a file share to SharePoint, the SharePoint 2010 Bulk Document Importer may be the tool for you. Why not just drag and drop files using the explorer view? This tool provides useful features that are an advantage over the out of the box document upload methods. For example, if you drag and drop a file from the file system into a document library, the name of the logged on user will be used for the last modified by. With this tool, the last modified information from the file system is retained. Other useful features include: logging, renaming illegally named files, and moving successfully migrated files to an archive folder.

SharePoint Log Viewer

The SharePoint Log Viewer has got to be one of the handiest ways to monitor SharePoint's Unified Logging Service (ULS) logs, and it is available for free. You can filter the logs by event id, level or category. In addition, you can set up email alerts to notify you if a certain severity of error is logged. If you are not a fan of receiving emails for problems logged on your server, then a less obtrusive system tray notification option is included.

WinForm SharePoint List Item Editing Tool

Use the WinForm SharePoint List Item Editing Tool if you want to work with SharePoint lists in batch. Without the need to create additional datasheet views, you can use this tool from your workstation to add and remove columns to a grid view. You can paste data from Excel and perform other batch functions such as checking in a selection of documents or importing a batch of documents. If you have event receivers on a list that fire when an item is added or modified, this tool will allow you to suppress those events when working in batch mode.

SPUtility.js

Still in alpha mode, the SPUtility.js project already offers features that are useful to power users and web developers. Unlike the SPServices jQuery Library for SharePoint, these JavaScript wrappers for SharePoint web services are based on the Prototype.js JavaScript framework and not on jQuery. The ideal use for this project is to get and set properties on the out of the box SharePoint list forms. You may get and set the value of a field. You may also change the properties of a field to make it read only, editable, visible, or hidden.

There are CodePlex projects for SharePoint that are worthy of mention, and more projects will likely surface in the near future. I encourage you to take a look at these projects and see how you may benefit from them on your SharePoint 2010 projects.