2 part question,

  • In my EmailReceived event receiver, what is the best way to pull out and save any attachments (whether they are .doc, .pdf, etc)
  • and then, when I have those attachments, save them to a different list

Currently in my event receiver I am pulling meta data successfully. Just not sure how to manage the attached files.



SPEmailMessage class (object of which is passed to EmailReceived method of your customer email event receiver). It has got Attachments property which contain all the attachments.

public override void EmailReceived(SPList list, SPEmailMessage message, string receiverData)
      // Get all the attachments in the root folder
      foreach (SPEmailAttachment attachment in message.Attachments)
             byte[] attachmentArray = new byte[attachment.ContentStream.Length];
             attachment.ContentStream.Read(attachmentArray, 0, (int)attachment.ContentStream.Length);
             list.RootFolder.Files.Add(attachment.FileName, attachmentArray);
  • I tried this, but when I the email appears in the document library I get a 'windat' file, even for emails that dont have attachments, and seems to break the service as I dont get any more mails coming in again, until I remove the code. A little off the topic, in the 3rd line can I use that code to rather dump the file in another list? If I want to manage my emails and documents in different lists. thanks! – Simon Apr 24 '15 at 7:51
  • Yes you can dump the file in another list. Get the list you needed for example get current web from SPContext.Current.Web or open a new web or site by url or id, then get needed list from this web and save attachments to it. About 'windata' you can check attachment type before saving it using attachment.ContentType property. For example: if (string.Equals(attachment.ContentType, "message/rfc822", StringComparison.OrdinalIgnoreCase)) - then it's msg file in attachments. And please mark it as correct answer if it helps you. – Andrey Ungur Apr 24 '15 at 12:16
  • Took me a while to eventually get back to this, but the provided solution worked. :) There is a case where that when emailing from Outlook, no matter what attachments you have (or dont have) the message.Attachments collection will always have a single 'winmail.dat' file. Couldn't find any way to get the actual attachments from out there. But when I send the same mail from GMail, they appear in the collection correctly. So I think this is another problem I need to investigate, but unrelated to this topic at hand. Thanks Andrey! – Simon May 6 '15 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.