如何从Winforms中的Outlook电子邮件中获取附件?

时间:2018-10-24 08:49:19

标签: c#

Microsoft.Office.Interop.Outlook.Application Application = new Microsoft.Office.Interop.Outlook.Application();

                    Microsoft.Office.Interop.Outlook.MAPIFolder inBox = Application.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
                    Microsoft.Office.Interop.Outlook.Items inBoxItems = inBox.Items;
                    Microsoft.Office.Interop.Outlook.MailItem newEmail = null;

                    foreach (object collectionItem in inBoxItems)
                    {
                        newEmail = collectionItem as Microsoft.Office.Interop.Outlook.MailItem;
                        if (newEmail != null)
                        {
                            if (newEmail.Attachments.Count > 0)
                            {
                                for (int i = 1; i <= newEmail
                                    .Attachments.Count; i++)
                                {
                                    newEmail.Attachments[i].SaveAsFile
                                        (@"C:\TestFileSave\" +
                                        newEmail.Attachments[i].FileName);
                                }
                            }
                        }
                    }

我已经从Outlook复制邮件并粘贴到window应用程序的flex-grid中,但是附件计数为零,但是邮件中有诸如excel,doc等文件的附件。

1 个答案:

答案 0 :(得分:0)

 int extractFileParentId = pkUniqueId;
        List<ZipExtracFile> extractFileList = lts;
        MsgReader.Outlook.Storage.Message message = new MsgReader.Outlook.Storage.Message(fileNames);

        foreach (var attachment in message.Attachments)
        {
            string fileName = string.Empty;
            pkUniqueId = pkUniqueId + 1;
            if (attachment.GetType() == typeof(MsgReader.Outlook.Storage.Attachment))
            {
                var attach = (MsgReader.Outlook.Storage.Attachment)attachment;
                fileName = Path.Combine(tempPath, (attach).FileName);

                File.WriteAllBytes(fileName, attach.Data);
                extractFileList.Add(new ZipExtracFile { pkUniqueId = pkUniqueId, fileName = fileName, parentId = extractFileParentId });

                if(Path.GetExtension(fileName).ToLower() == ".msg")
                {
                    ExtractMsgFile(fileName, ref pkUniqueId, ref tempPath, lts);
                }
            }
        }
        message.Dispose();

这用于从“ .msg”文件文档中提取文档,其中包含多级“ .msg”文件,并且可以在特定位置下载。为此,只需添加MsgReader.dll