How to move mail to a folder based on attachment filename?

穿精又带淫゛_ 提交于 2019-12-24 02:34:10

问题


I need a rule (or most probably a VBA macro) to sort my mails. In case I have per say "REPORT" in the filename of the attachment of a newly received mail than I would like to move that mail to a different folder, let say "REPORTS" folder.

How can I achieve this?

I already to set a rule on the mail header but that did not seem to solve the matter.

Thanks in advance!


回答1:


Used code from http://www.outlookcode.com/article.aspx?id=62 and http://blog.saieva.com/2010/03/27/move-messages-to-folders-with-outlook-vba/

'code goes in "ThisOutlookSession" module
Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    Dim arr() As String
    Dim i As Integer
    Dim ns As Outlook.NameSpace
    Dim itm As MailItem
    Dim m As Outlook.MailItem
    Dim att As Outlook.Attachment

    On Error Resume Next
    Set ns = Application.Session
    arr = Split(EntryIDCollection, ",")
    For i = 0 To UBound(arr)
        Set itm = ns.GetItemFromID(arr(i))
        If itm.Class = olMail Then
            Set m = itm
            If m.Attachments.Count > 0 Then
                For Each att In m.Attachments
                    If UCase(att.FileName) Like "*REPORT*" Then
                        MoveToFolder m, "MoveTest"
                        Exit For
                    End If
                Next att
            End If
        End If
    Next
    Set ns = Nothing
    Set itm = Nothing
    Set m = Nothing
End Sub


Sub MoveToFolder(mItem As MailItem, folderName)

 '###you need to edit this for your account name###
 Const mailboxNameString As String = "Mailbox - firstname lastname"

 Dim olApp As New Outlook.Application
 Dim olNameSpace As Outlook.NameSpace
 Dim olDestFolder As Outlook.MAPIFolder

 Set olNameSpace = olApp.GetNamespace("MAPI")
 Set olDestFolder = olNameSpace.Folders(mailboxNameString).Folders(folderName)

 Debug.Print "[" & Date & " " & Time & "] " & _
                ": folder = " & folderName & _
                "; subject = " & mItem.Subject & "..."

 mItem.Move olDestFolder

End Sub


来源:https://stackoverflow.com/questions/12283189/how-to-move-mail-to-a-folder-based-on-attachment-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!