What is the VBA (Visual Basic) code to fetch the mails from the outlook?

0 votes
asked Oct 31, 2015 in General by PradeepKumar_E (1,110 points)  

I am doing some visual basic code work. I need to know the code for the visual basic (VBA) code for fetching the mails from the outlook and i need to know the best way to learn the VBA basics from the website?


Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

1 Answer

0 votes
answered Feb 16, 2016 by tausif (190 points)  

Copy the declarations and code below and paste directly into your VB project.


Public Sub ProcessInbox()
Dim oOutlook As Outlook.Application
Dim oNs As Outlook.NameSpace
Dim oFldr As Outlook.MAPIFolder
Dim oAttachments As Outlook.Attachments
Dim oAttachment As Outlook.Attachment
Dim iMsgCount As Integer

Dim oMessage As Outlook.MailItem

Dim iCtr As Long, iAttachCnt As Long

Dim sFileNames As String
Dim aFileNames() As String

'get reference to inbox
Set oOutlook = New Outlook.Application
Set oNs = oOutlook.GetNamespace("MAPI")
Set oFldr = oNs.GetDefaultFolder(olFolderInbox)
Debug.Print "Total Items: "; oFldr.Items.Count
Debug.Print "Total Unread items = " & oFldr.UnReadItemCount

For Each oMessage In oFldr.Items
        With oMessage
        'basic info about message
            Debug.Print .To
            Debug.Print .CC
            Debug.Print .Subject
            Debug.Print .Body
            If .UnRead Then
                Debug.Print "Message has not been read"
                Debug.Print "Message has been read"
            End If
            iMsgCount = iMsgCount + 1
            'save message as text file
            .SaveAs "C:\message" & iMsgCount & ".txt", olTXT

            'reference and save all attachments
            With oMessage.Attachments
                iAttachCnt = .Count
                If iAttachCnt > 0 Then
                    For iCtr = 1 To iAttachCnt

            .Item(iCtr).SaveAsFile "C:\" & .Item(iCtr).FileName

                    Next iCtr
                End If
            End With
        End With

    Next oMessage
    Set oAttachment = Nothing
    Set oAttachments = Nothing
    Set oMessage = Nothing
    Set oFldr = Nothing
    Set oNs = Nothing
    Set oOutlook = Nothing
End Sub

For Learning VBA I suggest you the following sites




I hope you would like this

198 questions

179 answers


183 users

Most active Users
January 2018:

    Recent Badges

    Notable Question
    - pythonskynet -
    100 Club
    - hassanjaved10 -
    Popular Question
    - 3aalakkannan -
    100 Club
    - Namdev hole -
    100 Club
    - yfewakog -