Read attachments from Outlook (1 Viewer)


Registered User.
Local time
Today, 10:29
Jul 23, 2012
I would appreciate your help with the folowing code, wich retrieves jpg files sent to a folder in my Outlook email account, and it works just fine, but if instead of receving a email with a image attachment, I just drag and drop a jpg file into the Outlook folder the code wont recognize that attachment. Anyway I can do that ?
Thanks for your help.

Dim db As DAO.Database
Dim ns As Namespace
Dim Inbox As MAPIFolder
Dim FileName As String
Dim i As Integer, N As Integer, R As Integer
Dim objSearchFolder As Outlook.MAPIFolder
Dim item As MailItem
Dim atmt As Outlook.Attachment

Dim strSQL As String
Dim rst As DAO.Recordset

Set db = CurrentDb()
Set ns = GetNamespace("MAPI")
Set rst = db.OpenRecordset("tblDocs", dbOpenDynaset)

Set Inbox = ns.GetDefaultFolder(olFolderInbox)
Set objSearchFolder = Inbox.Folders("docs")
'Debug.Print objSearchFolder.Items.Count
i = 0

If objSearchFolder.Items.Count = 0 Then
    MsgBox "Nao existem emails Novos", vbInformation, "Sem Dados"
    Exit Sub
End If

N = 1
For Each item In objSearchFolder.Items

        For Each atmt In item.Attachments
     Debug.Print N & " de " & item.Attachments.Count
                FileName = "C:\eu\docs\docsArq\Pag " & N & "_" & atmt.FileName
                atmt.SaveAsFile FileName
               strSQL = "INSERT INTO tblDocs(docPath)" & _
                    "VALUES ('" & FileName & "')"
               DoCmd.RunSQL strSQL
            If Len(FileName) > 0 Then N = N + 1
            i = i + 1
        Next atmt
    Next item

set objSearchFolder = Nothing
Set Inbox = Nothing
Set ns = Nothing

If i > 0 Then
    MsgBox (N - 1 & " Documents added")
    MsgBox ("No Documents")
End If


Lifelong Learner
Local time
Today, 10:29
Mar 14, 2017
I think you'll have to expand from item being a mailitem to item being something else.
What something else?
You can begin your investigation by clicking "Debug" on the runtime error that I think you probably are currently getting as soon as the code hits that non-mailitem item.
Once you've clicked Debug, View the Immediate Window and ask it this question:

?TypeName(item) [then hit Enter]

Then, once you find this out, you can begin to alter your code in order to test for the type, "something else". if typename(item)="MailItem" (then set a variable you've predeclared as a MailItem and act appropriately, using IT'S methods and properties). If typename(item")="something else" then (then set a variable you've predeclared as that SomethingElse and act appropriately, using IT'S method and properties, which likely won't be the same as the Attachments.count, etc., but might be - will require reading MSDN documentation


Registered User.
Local time
Today, 10:29
Jul 23, 2012
Thanks Isaac, for pointing me to the solution, I already noticed that ?TypeName(item), returns "DocumentItem"
I will let you know if I can figure this out

Users who are viewing this thread

Top Bottom