Outlook自定义插件代码无法正常工作(下载电子邮件附件)

时间:2015-02-12 14:46:22

标签: outlook

我想要从外接的邮件中保存附件。这是我的代码。我的问题是它在电子邮件到达时(当我的笔记本电脑打开时)正确下载,但是这封邮件每天早上6点安排,我打开笔记本电脑9点,邮件已经存在,而且没有按预期下载?我是需要用代码做什么吗?

const string destinationDirectory = @"\\prod_data\Service Now\";

            Outlook.MAPIFolder inBox = this.Application.ActiveExplorer()
                 .Session.GetDefaultFolder(Outlook
                 .OlDefaultFolders.olFolderInbox);
            Outlook.Items inBoxItems = inBox.Items;
            Outlook.MailItem newEmail = null;
            inBoxItems = inBoxItems.Restrict("[Unread] = true");
            try
            {
                foreach (object collectionItem in inBoxItems)
                {
                    newEmail = collectionItem as Outlook.MailItem;

                    if (newEmail != null)
                    {
                        if (newEmail.Attachments.Count > 0)
                        {
                            for (int i = 1; i <= newEmail
                               .Attachments.Count; i++)
                            {

                                if (newEmail.Attachments[i].FileName.Contains( "LogicView Issue Report"))
                                {

                                    newEmail.Attachments[i].SaveAsFile(destinationDirectory +
                                        newEmail.Attachments[i].FileName);

                                }
                            }
                        }
                    }
                }
            }

2 个答案:

答案 0 :(得分:0)

我建议查看MarkForDownload属性值。它返回一个OlRemoteStatus常量,该常量确定远程用户收到项目后的状态。例如:

Sub DownloadItems()
  Dim mpfInbox As Outlook.Folder  
  Dim obj As Object  
  Dim i As Integer 
  Set mpfInbox = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)  
  'Loop all items in the Inbox folder  
  For i = 1 To mpfInbox.Items.Count  
    Set obj = mpfInbox.Items.Item(i)  
   'Verify if the state of the item is olHeaderOnly  
   If obj.DownloadState = olHeaderOnly Then  
     MsgBox ("This item has not been fully downloaded.")  
    'Mark the item to be downloaded.  
    obj.MarkForDownload = olMarkedForDownload  
  End If  
  Next  
End Sub

您可以使用SyncObject类的Start方法开始使用指定的Send \ Receive组同步用户的文件夹。

答案 1 :(得分:0)

不要使用Application.NewMail事件 - 仅当Outlook在Exchange服务器收到电子邮件时运行时才会触发该事件。

在收件箱文件夹(Items.ItemAdd)上使用Namespace.GetDefaultFolder(olFolderInbox)事件 - 当Outlook同步收件箱文件夹时(假设您使用的是缓存模式),当电子邮件下载到缓存存储时,它将会触发。如果Outlook处于联机状态,则不会触发任何事件。在这种情况下,您可以使用Items.Find/FindNext处理所有未读邮件([Unread] = 'true'。)

//declare on the global/class level to make sure 
//it does not get garbage collected
private Outlook.Items inBoxItems;
...
//in your addin startup code
inBoxItems = inBox.Items
inBoxItems.ItemAdd += inboxItemsItemAdd;
...
private void inboxItemsItemAdd(object item)
{
...
}