Home > Blogs > Blog Post

Code Sample : How to programmatically send an email in SharePoint

by Mark Jones | Dec 27, 2011

If your SharePoint farm has been configured to use an SMTP server, then it is possible to send an email in code using the SPUtility class. The c# code below illustrates how to send a mail and return an XML string outlining what was sent for logging purposes :

public static string SendEmail(
    SPWeb spWeb,
 string from,
 string to,
 string cc,
 string bcc,
 string subject,
 string body,
 bool isBodyHtml)
{
    LogHelper.LogMethodStart(logger, "SPEmailHelper", "SendEmail");
 
 string emailSummary;
 
 var messageHeaders = new StringDictionary();
 
    ValidationHelper.VerifyStringArgument(to, "to");
    ValidationHelper.VerifyStringArgument(from, "from");
    ValidationHelper.VerifyStringArgument(subject, "subject");
    ValidationHelper.VerifyStringArgument(cc, "cc");
    ValidationHelper.VerifyStringArgument(bcc, "bcc");
 
    messageHeaders.Add("to", to);
    messageHeaders.Add("from", from);
    messageHeaders.Add("subject", subject);
    messageHeaders.Add("cc", cc);
    messageHeaders.Add("bcc", bcc);
 
 string mimeType = "text/plain";
 if (isBodyHtml)
    {
        mimeType = "text/html";
    }
 
    messageHeaders.Add("content-type", mimeType);
 
 bool sendMail = SPUtility.SendEmail(
        spWeb,
        messageHeaders,
        body);
 
 if (sendMail)
    {
        emailSummary = "<EmailMessage>" +
 "<To>" + to + "</To>" +
 "<From>" + from + "</From>" +
 "<Subject>" + 
                        SPEncode.HtmlEncode(subject) + 
 "</Subject>" +
 "<CC>" + cc + "</CC>" +
 "<BCC>" + bcc + "</BCC>" +
 "<Body>" + 
                        SPEncode.HtmlEncode(body) + 
 "</Body>" +
 "</EmailMesage>";
    }
 else
    {
 throw new SafException("Failed to send email.");
    }
 
    LogHelper.LogMethodEnd(logger, "SPEmailHelper", "SendEmail");
 return emailSummary;
}

Compliance using DocRead

DocRead logoDocRead for SharePoint can help you manage policy compliance by:

  • Targeting documents or policies at specific groups of users
  • Allowing a specific amount of time for users to confirm agreement 
  • Sending email reminders when policy compliance is overdue
  • Users self-certify that they have read and fully understood the policy details
  • Securely storing records of confirmed policy acceptance
  • Monitoring the user acceptance of policies via a reporting suite
  • Providing detailed reading reports and statistics
  • Report drill through to show who has not accepted the policy
  • Automatically sending historic compliance tasks and policies to new users when they are added to a group
  • Bringing policy compliance requests immediately to users attention when they log on

DocRead is simple to install and configure. It seamlessly integrates with SharePoint and can be added to any existing SharePoint site.

To find out more, visit the DocRead product site.


blog comments powered by Disqus