Search code examples
vbaoutlookoutlook-2010outlook-filter

Download attachments from From UnRead Items and are from specific sender


I want to download all attachments from emails which are both unread and received from the specific sender in MS Outlook.

I found a code, which downloads all attachments from all unread emails. Downloading Attachments from Unread Emails of MS Outlook and tried to adapt it.

However, filter is not working properly. It shows that there are no such e-mails.

Filter = "[Unread] = True And [SenderEmailAddress] = 'yrybchuk@gmail.com'"

Below is the entire code:

Option Explicit
Public Sub Example()
Dim oOlAp As Object
Dim olNs As Outlook.Namespace
Dim Inbox As Outlook.MAPIFolder
Dim Items As Outlook.Items
Dim Item As Outlook.MailItem
Dim Atmt As Attachment
Dim Filter As String
Dim FilePath As String
Dim AtmtName As String
Dim i As Long

'// Set Inbox Reference
Set oOlAp = GetObject(, "Outlook.application")
Set olNs = oOlAp.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)

FilePath = "C:\Users\irybchuk\Documents\"
Filter = "[Unread] = True And [SenderEmailAddress] = 'yrybchuk@gmail.com'"
Set Items = Inbox.Items.Restrict(Filter)

'// Loop through backwards
For i = Items.Count To 1 Step -1
    Set Item = Items.Item(i)

    DoEvents

    If Item.Class = olMail Then
        Debug.Print Item.Subject ' Immediate Window

        For Each Atmt In Item.Attachments
            AtmtName = FilePath & Atmt.FileName
            Atmt.SaveAsFile AtmtName
        Next
    End If
Next

Set Inbox = Nothing
Set Items = Nothing
Set Item = Nothing
Set Atmt = Nothing
Set olNs = Nothing
End Sub

I believe that here: How to filter items sendername from Items_ItemAdd Events? could be described possible solution how to change filter line. However, I couldn't do it.


Solution

  • Your filter seems to work for me but here is different one SQL DASL syntax you can use

    Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:fromname" & _
                       Chr(34) & " Like '%yrybchuk@gmail.com%' AND " & _
                       Chr(34) & "urn:schemas:httpmail:read" & _
                       Chr(34) & "=0"
    

    Or better yet one with the attachment Restricted Filter to improve your loop

    Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:fromname" & _
                       Chr(34) & " Like '%yrybchuk@gmail.com%' AND " & _
                       Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                       Chr(34) & "=1 AND " & _
                       Chr(34) & "urn:schemas:httpmail:read" & _
                       Chr(34) & "=0"
    

    remember to update %yrybchuk@gmail.com%

    FYI
    If code is being run from Outlook then you don't need
    oOlAp = GetObject(, "Outlook.application")