Skip to main content

Mark Wagner - Cogitation Blog

Go Search
Blog
SPDev
SharePoint
Governance
  

Welcome
Mark Wagner works for Microsoft as a Consultant working in the West Region.
My old blog
Mark Wagner - Cogitation Blog > Posts > SharePoint RunWithElevatedPrivileges Example
SharePoint RunWithElevatedPrivileges Example

The following example sends an email using elevated privileges.  This will elevate the privileges to execute using the service account.

The SPSecurity.RunWithElevatedPrivileges method taks a delegate method as its argument and executes that code with the service account.

SPSecurity.RunWithElevatedPrivileges(
    delegate()
    {
        // Your code needing elevated permissions goes here.
    }
)

public void SendEmail(Email email)
{
   SPSecurity.RunWithElevatedPrivileges(
      delegate()
      {
         SmtpClient mail = new SmtpClient();
         MailMessage message = new MailMessage();
 
         message.From = new MailAddress(this.SenderAddress);
 
         message.To.Add(email.To);
         message.IsBodyHtml = email.IsHtml;
 
         if (!string.IsNullOrEmpty(email.Cc))
            message.CC.Add(email.Cc);
 
         if (!string.IsNullOrEmpty(email.Bcc))
            message.Bcc.Add(email.Bcc);
 
         if (!string.IsNullOrEmpty(this.ReplyToAddress))
             message.ReplyTo = new MailAddress(this.ReplyToAddress);
 
         if (!string.IsNullOrEmpty(email.Subject))
            message.Subject = email.Subject;
 
         if (!string.IsNullOrEmpty(email.Body))
            message.Body = email.Body;
 
         mail.Host = this.CentralAdminOutboundServerAddress;
         mail.Send(message);
      }
   );
}

Comments

Thanks and two questions

Thanks for posting the code example Mark. What script are you using on WebHost4life for code examples? It looks great and I can't install server side assemblies.
Also, can you talk about the benefits of doing this over some other type of emailing from SharePoint?
at 7/15/2009 9:39 AM

Add Comment

Items on this list require content approval. Your submission will not appear in public views until approved by someone with proper rights. More information on content approval.

Title


Body *


Today's Date *

Please enter today's date. This will help prevent blog spam. Thank you.
Attachments