2017-02-21 83 views
0

不確定爲什麼以下代碼不會永久刪除Deleted Items文件夾中的MailItemMailItem.Delete拒絕刪除已刪除郵件文件夾中的郵件

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 
+0

可能因爲這就是刪除操作...將其移動到刪除的文件夾。如果您的Outlook設置爲關閉時刪除它們,它們在關閉時應該消失。否則,他們會留在那裏。 –

+0

你可能想檢查這個鏈接http://www.vbforums.com/showthread.php?327965-RESOLVED-Permanently-Delete-Outlook-Items –

+0

或者這個https://www.experts-exchange.com/questions /27503590/VBA-to-permanently-delete-emails-instead-of-moving-them-to-the-deleted-folder.html –

回答

1

要永久地通過Items刪除MailItem你必須環路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 

我的代碼將有所不同,以你的,因爲我已經把選項嚴格上。我建議你這樣做。這將從長遠來看有所幫助。

請注意,我將UserProperty設置爲MailItem,然後將其移至Deleted文件夾。這將有助於識別您想要永久刪除的單個MailItem如果要在Deleted文件夾中永久刪除所有MailItems那麼這就是你需要的代碼:

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) 。