Sing Hua Young

Share to Learn

导航

Exchange Web Service 获取邮件的附件并保存到本地的示例代码

 private static void DownLoadMailAttachments(ExchangeService service, ItemId itemId)
        {
            EmailMessage message = EmailMessage.Bind(service, itemId, new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.Attachments)); ;

            if (message.HasAttachments)
            {
                foreach (MailAttachment attachment in message.Attachments)
                {
                    FileAttachment fileAttachment = attachment as FileAttachment;

                    ItemAttachment itemAttachment = attachment as ItemAttachment;

                    if (itemAttachment != null)
                    {
                        itemAttachment.Load(EmailMessageSchema.MimeContent);

                        char[] invalidChars = Path.GetInvalidPathChars();
                        string name = itemAttachment.Name;

                        foreach (char invalidChar in invalidChars)
                        {
                            name = name.Replace(invalidChar, ' ');
                        }

                        name = name.Replace(":", " ");

                        string emailPath = Path.Combine(Path.GetTempPath(), name + ".eml");

                        using (FileStream stream = File.Open(emailPath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            foreach (byte content in itemAttachment.Item.MimeContent.Content)
                            {
                                stream.WriteByte(content);
                            }
                        }

                      
                    }

                    if (fileAttachment != null)
                    {
                        string filePath = Path.Combine(Path.GetTempPath(), fileAttachment.Name);

                        fileAttachment.Load();

                        using (FileStream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            foreach (byte content in fileAttachment.Content)
                            {
                                stream.WriteByte(content);
                            }
                        }
                    }
                }
            }

        }

 

posted on 2013-08-29 11:56  N洋葱Py  阅读(1105)  评论(0编辑  收藏  举报