Friday, 10 May 2013

Download Attachments From Email In Outlook To Local System.


                                          Download Attachments From Email
You can download the  attached item of emails in outlook and save it  some where. Just try this
code in your local system.
     
        Dim objOutlook As New Outlook.Application
        Dim objNS As Outlook.NameSpace = objOutlook.GetNamespace("MAPI")
        Dim objInboxFolder As Outlook.MAPIFolder = Nothing
        Dim objXYZFolder As Outlook.MAPIFolder = Nothing
        Dim objFailedFolder As Outlook.MAPIFolder = Nothing
        Dim emails As Items
        Dim email As MailItem
        Dim Num_mails As Integer = 0
        Dim email_attachment As Attachment
        Dim extension As String

        objInboxFolder = objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
        objXYZFolder = objInboxFolder.Folders("Valuehire")
        objFailedFolder = objXYZFolder.Folders("Failed")

        emails = objXYZFolder.Items
        Num_mails = emails.Count

        Dim MyDocumentsDir As String = vbNull
        Dim DownloadDirName As String = vbNull
       
        MyDocumentsDir = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        DownloadDirName = MyDocumentsDir + "\Outlook Files\Valuehire\Downloads"

        If Num_mails > 0 Then
            For Each email In emails
                If email.Class = OlObjectClass.olMail Then
                    For Each email_attachment In email.Attachments
                        Dim filename As String = DownloadDirName + "\" + email_attachment.FileName
                        extension = Path.GetExtension(email_attachment.FileName)

                        If (extension = ".doc" Or extension = ".docx" Or extension = ".pdf" Or extension = ".rtf") Then
                            Try
                                email_attachment.SaveAsFile(filename)                               
                                MsgBox("File is downloaded")
                                Catch ex As System.Exception
                                If ex.Message.Contains("530") Then
                                    MsgBox("Your account is invalid. Please try again or contact your Administrator.")                                   
                                Else
                                     MsgBox("File is not downloaded")                                   
                                End If
                                Return
                            End Try
                        End If
                    Next email_attachment
                End If
            Next email
        End If

Notes- You can see above, in the first underline is pointed  to destination place where the file
 is store and second one for save the file in destination folder.

No comments:

Post a Comment