October 11, 2010

Extension Method to Send HTML Emails in SharePoint

You can use this method to extend SPWeb to send HTML email and lets you specifies the From, To, CC, Bcc, subject and body of the email and uses the out of the box SPUtility.SendEmail to send the email (without the need to specify all details of the mail server)
/// <summary>
/// Sends an email to the selected users
/// </summary>
/// <param name="web">The web.</param>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <param name="cc">The cc.</param>
/// <param name="bcc">The BCC.</param>
/// <param name="subject">The subject.</param>
/// <param name="body">The body.</param>
/// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
public static void SendEmail(this SPWeb web, string from, string to,
string cc, string bcc, string subject, string body,
bool isHtml)
    // <pex>
    if (web == null)
        throw new ArgumentNullException("web");
    if (string.IsNullOrEmpty(to))
        throw new ArgumentNullException("to");
    if (string.IsNullOrEmpty(subject))
        throw new ArgumentNullException("subject");
    if (string.IsNullOrEmpty(body))
        throw new ArgumentNullException("body");
    // </pex>
    if (!string.IsNullOrEmpty(to))
        var headers = new StringDictionary
                {"to", to},
                {"subject", subject},
                {"content-type", isHtml ? "text/html" : "text/plain"}
        if (!string.IsNullOrEmpty(from)) headers.Add("from", from);
        if (!string.IsNullOrEmpty(cc)) headers.Add("cc", cc);
        if (!string.IsNullOrEmpty(bcc)) headers.Add("bcc", bcc);
        SPUtility.SendEmail(web, headers, body);

1 comment: