Quantcast
Channel: SharePoint 2010 - Development and Programming forum
Viewing all articles
Browse latest Browse all 11571

Logic to send out email notifications when documents are added to a library

$
0
0

I am trying to come up with a logic that will send out emails to specified addresses when a document is added to a library. So far I have come up with this code

public override void ItemAdded(SPItemEventProperties properties)
{
   try
   {
	   SPSecurity.RunWithElevatedPrivileges(delegate()
	   {
		   using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
		   {
			   using (SPWeb currentWeb = currentSite.OpenWeb(SPContext.Current.Web.ID))
			   {

				   SPFolder mylibrary = properties.Web.Folders["My Docs"];
				   properties.Web.AllowUnsafeUpdates = true;
				   SmtpClient smtpClient = new SmtpClient("smtpserver.com");
				   smtpClient.Send(BuildMailMessage(myItems));

			   }
		   }
	   });
   }
   catch (Exception ex)
   {
	   properties.ErrorMessage = string.Format("An error occurred during execution of ItemAdding event: {0}.", ex.Message);
	   properties.Status = SPEventReceiverStatus.CancelWithError;
	   properties.Cancel = true;
   }
   finally
   {

   }

}

private MailMessage BuildMailMessage(SPListItem item)
{
   MailMessage message = new MailMessage();
   SPList list = item.ParentList;
   message.From = new MailAddress("myemailaddress@mycompany.com");
   message.To.Add(new MailAddress("recipient@theircompany.com"));
   message.IsBodyHtml = true;
   message.Body = "Please review the following attachment for details";
   message.Subject = "Word document received";

   for (int attachmentIndex = 0; attachmentIndex < item.Attachments.Count; attachmentIndex++)
   {
	   string url = item.Attachments.UrlPrefix + item.Attachments[attachmentIndex];
	   SPFile file = list.ParentWeb.GetFile(url);
	   message.Attachments.Add(new Attachment(file.OpenBinaryStream(), file.Name));
   }

   return message;
}
When i build this, I keep getting an error that states "The name 'myItems' does not exist in the current context". Any ideas on how i can get this fixed? 


Viewing all articles
Browse latest Browse all 11571

Trending Articles