从源文件夹复制电子邮件(如果目标文件夹中不存在)

问题描述:

我正在使用Visual Studio构建用于复制电子邮件的插件.

I'm using Visual Studio to build an addin to copy emails.

条件是根据SentOn/ReceivedTime检查并仅复制源文件夹中目标文件夹中不存在的那些电子邮件.

The condition is to check, according to SentOn/ReceivedTime, and copy only those emails from the source folder that do not exist in the destination folder.

我尝试下面的代码,但它给我一个错误System.OutOfMemoryException Out of memory or system resources.

I tried below code but its gives me an error System.OutOfMemoryException Out of memory or system resources.

Sub CopyMail(SourceFolder As Outlook.Folder, DestinationFolder As Outlook.Folder)
    Dim sMail As Object
    Dim dMail As Object
    Dim MailC As Object
    For Each sMail In SourceFolder.Items
        For Each dMail In DestinationFolder.Items
            If sMail.SentOn <> dMail.SentOn Then
                MailC = sMail.Copy
                MailC.Move(DestinationFolder)
            End If
        Next
    Next
End Sub

嵌套循环中存在逻辑错误-对于目标文件夹中的每个项目,您都复制了源文件夹中的所有不匹配项,即使这些项可能匹配目标文件夹中的其他项目.

There is a logic error in your nested loop - for each item in the destination folder you copy all non-matches from the source folder, even though those items may match other items in the destination folder.

这是一种可行的方法(未经测试). 在VBA中:我的VB.NET不好,无论如何都用VBA标记了...

Here's an approach (untested) which should work. It's in VBA: my VB.NET is not good and anyway you tagged with VBA...

Sub CopyMail(SourceFolder As Outlook.Folder, DestinationFolder As Outlook.Folder)
    Dim sMail As Object
    Dim dMail As Object
    Dim MailC As Object
    Dim dictSent As New Scripting.dictionary, i As Long

    'get a list of all unique sent times in the
    '  destination folder
    For Each dMail In DestinationFolder.Items
        dictSent(dMail.SentOn) = True
    Next

    'loop through the source folder and copy all items where
    '  the sent time is not in the list
    For i = SourceFolder.Items.Count To 1 Step -1
        Set sMail = SourceFolder.Items(i)

        If Not dictSent.Exists(sMail.SentOn) Then
            Set MailC = sMail.Copy        'copy and move
            MailC.Move DestinationFolder
            dictSent(sMail.SentOn) = True 'add to list
        End If

    Next i

End Sub