Code Sample : How to programmatically send an email in SharePoint

by Mark Jones | Nov 06, 2012

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;
}


Have your say ...

blog comments powered by Disqus
Collaboris RSS Feed

RSS Feed

To get updated as we blog - get the feed.

Read & Sign in SharePoint