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.
    }
)

Example:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s