Skip to main content

Mark Wagner - Cogitation Blog

Go Search
Blog
SPDev
SharePoint
Governance
  

Mark Wagner - Cogitation Blog > Categories
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);
      }
   );
}