MailItem.Delete拒绝删除已删除邮件文件夹

时间:2017-02-21 06:02:48

标签: vb.net mailitem

不确定以下代码为何不会从MailItem文件夹中永久删除Deleted Items

MailItem肯定会在Deleted Items文件夹中结束,但Delete似乎什么都不做。放置第二个Delete会导致异常,因为它不存在。

我可以通过Outlook永久地手动删除MailItem

代码:

Dim oOLapp as Outlook.Application
Dim oMapi as Outlook.NameSpace
Dim oFolder as Outlook.Folder
Dim oMailItem as Outlook.MailItem

oOLapp = GetObject([Class]:="Outlook.Application")
oMapi = oOLapp.GetNameSpace("MAPI")
oFolder = oMapi.oFolders(oMapi.DefaultStore.Displayname).Folders("Deleted Items")

oMailItem = oOLapp.Session.OpenSharedItem("C:\sometestmail.msg")
oMailItem = oMailItem.Move(oFolder) ' Now in Deleted items Folder. Verified
' Do other stuff with email
' .
' .
' .
oMailItem.Delete()
oMailItem = nothing

1 个答案:

答案 0 :(得分:1)

要永久删除MailItem,您必须遍历Items文件夹中的Deleted

要执行此操作,请查看以下代码:

Dim oApp As New Outlook.Application

Dim oMapi As Outlook.NameSpace = oApp.GetNamespace("MAPI")
Dim oFolders As Outlook.Folders = oMapi.Folders
Dim oFolder As Outlook.MAPIFolder = oFolders(oMapi.DefaultStore.DisplayName).Folders("Deleted Items")

Dim oMailItem As Outlook.MailItem = CType(oApp.Session.OpenSharedItem("C:\sometestmail.msg"), Outlook.MailItem)
oMailItem.UserProperties.Add("DeleteMe", Outlook.OlUserPropertyType.olText)
oMailItem.Move(oFolder)
oMailItem = Nothing

For Each item As Outlook.MailItem In oFolder.Items
    Dim oProperty As Outlook.UserProperty = item.UserProperties.Find("DeleteMe")

    If oProperty IsNot Nothing Then
        item.Delete()
    End If
Next

我的代码与您的代码不同,因为我已将 Option Strict On 。我建议你这样做。从长远来看,这将有所帮助。

请注意,我将UserProperty设置为MailItem,然后再将其移至Deleted文件夹。这有助于识别您要永久删除的单个MailItem如果您要永久删除MailItems文件夹中的所有Deleted,那么这就是您需要的代码:

Dim oApp As New Outlook.Application

Dim oMapi As Outlook.NameSpace = oApp.GetNamespace("MAPI")
Dim oFolders As Outlook.Folders = oMapi.Folders
Dim oFolder As Outlook.MAPIFolder = oFolders(oMapi.DefaultStore.DisplayName).Folders("Deleted Items")

Dim oMailItem As Outlook.MailItem = CType(oApp.Session.OpenSharedItem("C:\sometestmail.msg"), Outlook.MailItem)
oMailItem.Move(oFolder)
oMailItem = Nothing

For i = oFolder.Items.Count To 1 Step -1
    CType(oFolder.Items(i), Outlook.MailItem).Delete()
Next

为了实现此目的,您需要向后遍历Deleted文件夹 。查看它所声明的MSDN文档:

  

Delete方法删除集合中的单个项目。要删除文件夹的Items集合中的所有项目,必须删除从文件夹中的最后一项开始的每个项目。例如,在文件夹的项目集合AllItems中,如果文件夹中有n个项目,则开始删除AllItems.Item(n)中的项目,每次递减索引,直到删除AllItems.Item(1)