outllook  how to downlod a file from a email link

Posted on 2007-07-24
Last Modified: 2008-03-06
hi outlook experts, I have a email arrives on my server that I use Outllok to down load the email form my mailserver. I have code that will find and extract an attachment and then save it to my hard disk. But the system uses performs through Joomla to up load an email with a file attached.
But the file does not arrive as an attachment but arrives as a link ie...

First Name D
Last Name nighti
Company newpos
Email address
Attach Text File
  ***** this is the file that I wish to down load to my hard drive*****

now if this came as a attachement I could grab it and save it.
But what I need is the object code that will allow me to disect the object module and then down load the file as a data stream or what ever method works and save it as a file.  
I am guessing that I am not the first to run in to this problem, and have search for the last couple of hours with no success. So any one that has a solution or can point me in the right direction I would be most gratefull

Question by:sydneyguy
    LVL 59

    Accepted Solution

    Don't know of a specific process to do this but a few thoughts:

    Using a macro and the newmailex event it is possible to access the mail .body and process it to find a link. For instance:

    Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    Dim strEntryId() As String
    Dim intFinal As Integer
    Dim mai As Object
        strEntryId = Split(EntryIDCollection & ",", ",")
        For intFinal = 0 To UBound(strEntryId) - 1
            Set mai = Application.Session.GetItemFromID(strEntryId(intFinal))
            If Not mai Is Nothing Then
                Debug.Print "Received email with " & mai.Attachments.Count & " Attachments."
                If mai.BodyFormat <> olFormatPlain Then
                    mai.BodyFormat = olFormatPlain
                End If
                If InStr(1, mai.Body, "http:") Then Debug.Print "mail received with a link"
            End If

    End Sub

    If you know for instance that every email link has this format then you can extract the link to text so the next requirement will be to follow the link and save the file itself.  I have seen solutions on the site for downloading files on the internet so I think that can also be resolved so as a starter can you identify formats, (i.e. a pattern) for any links that you want to save?


    Author Comment

    do you have the calling code to this so that I can get it running with out having to figure out the substute varable statements to define that statement
    thanks ....

    Author Comment

    ok have that figured out now have set it up to actually fire when a new file arrives thus the no need for calling object, It has been a while playing with outlook

    Author Comment

    ok not going yet I found that the system did not run when a  new http link arrived I found an article that memtioned that this should be set
    Now, before you put this in the Macro Editor you also probably need to go into Tools, References and go down to "Microsoft XML 6.0" and "Microsoft ActiveX Data Objects 2.8 Library" and enable both those.  I would enable "Microsoft VBScript Regular Expressions 5.5" and actually replace much of the above code with Regex expressions
    have sett these but find the system will still not auto run on receipt of a new mail message with a http link attached, thats with it running your code
    any ideas ???

    Author Comment

    Ok bit more info the system mail file does not arrive with an attached http link but it actually comes in as a
    mail body subject area and the below comes in a text inside the body area, so the http link will not triger the extract. May need to pull apart the body and extract the info required

    Item Value
    First Name h
    Last Name h
    Company h
    Email address
    Attach Text File
    any code to read the body of the mail doc. I have gone down to try and disect the object structure for outlook mail object butit all takes time, could use a point in the right dir

    LVL 59

    Expert Comment

    by:Chris Bottomley
    Sorry, wrong end of my day!

    If the link is in the subject area then:

        Set mai = Application.Session.GetItemFromID(strEntryId(intFinal))
            If Not mai Is Nothing Then
                If InStr(1, mai.subject, "http:") Then Debug.Print "mail received with a link"

    It may take time to iron out the scenario but at least in terms of establishing the link string I am sure we can do it as long as we have a format that identifies the specific messages from any chaff you may receive.


    Author Comment

    I have now got the link down loaded and can read any part of the file that is in the body which means that I can include any info in the body from the web page and extract the information. So this is good and working fine.
    the code that is working although not clean runs from here

    Private Sub Application_NewMail()  '<-- this must be in the 'ThisOutlookSession'
    writeSubject                                 '<-- in the Microsoft Objects Project Folder
    End Sub                                       '<--

    Public Sub writeSubject()
    Dim Str As String
    Dim pos1 As Integer
    Dim LenYourStr As Integer
    Dim YourStr As String

    Dim Res As String
    Dim ns As NameSpace
    Dim Inbox As MAPIFolder
    Dim message As MailItem
    Dim filename As String
    YourStr = "Attach Work Flow Text File"
    Set ns = GetNamespace("MAPI")
    Set Inbox = ns.GetDefaultFolder(olFolderInbox)
    Set message = Inbox.Items(1)
    MsgBox (Inbox.Items(1))
    MsgBox (message.Body)

    YourStr = "Attach Work Flow Text File" ''''' Your full string
    LenYourStr = Len(YourStr)
    Str = message.Body    '''''' Hello the weather is warm here:
    pos1 = InStr(message.Body, "Attach Work Flow Text File")
    Res = Mid(Str, 73 + 1 + 26, Len(Str) - LenYourStr + pos1)
         '   End If
    Trim (Res)
    MsgBox (Res)
    Dim sFile
    sFile = Res

    'To here ****************************************************************
    ' now as you suggested before I need the code to extract the file and save it on my local drive
    ' **************************************************************************


    'CommonDialog Control


    'sFile = Mid(sFile, 9) 'get a clean full path & file name

    '  With CommonDialog1
     '   .Action = 2
     '   .DialogTitle = "Save File"
     '   .InitDir = ""
     '   .Filter = "Saved Files (*.htm)|*.htm"
     '   .FilterIndex = 1
     '   .Flags = cdlOFNNoValidate + cdlOFNHideReadOnly + lOFNExplorer
     '   .filename = "testname.txt" 'ParsePath(sFile, 6)
     '   .ShowSave
     '   sFile = .filename
     ' End With

     Dim furl
     Dim filn
     Dim XH
     Dim X
     Dim XG
        If Left(Res, 7) = "http://" Then
                furl = Res   '' this should turn out to be ""
                filn = "C:\Media\" & Mid(furl, InStrRev(furl, "/") + 1) '' this just tries to figure out a filename... so from above
                Set XH = CreateObject("Microsoft.XMLHTTP") '' use "Microsoft XML 6.0" to download
                XH.Open "GET", furl, 0
                X = XH.Send()
                Set XG = CreateObject("ADODB.Stream") '' use "Microsoft ActiveX Data Objects 2.8 Library" to save to decode and save to disk
                XG.Mode = 3: XG.Type = 1
                X = XG.Open()
                XG.Write (XH.responseBody)
                XG.SaveToFile filn, 2
               ' Exit For    '' only download first link found
        End If

    End Sub
    LVL 59

    Expert Comment

    by:Chris Bottomley
    I have been looking for generic save off the web applications and have so far failed, I have opened xls files but as yet now figured out how to download the file itself ready for saving.  I presume from your bit of code, (If Left(Res, 7) = "http://" Then etc.) that you know a lot more than I so if there is some specific you need an assist with then i'll try and help, otherwise i'll search until I maybe find something I can understand and see if you have a solution for the second leg of your problem ... for now though just glad I was able to help with the first part, and sorry getting the second part working may take a little longer.

    LVL 59

    Expert Comment

    by:Chris Bottomley
    Just found this ...

    Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
    Private Sub Form_Load()
        Dim sSrc As String, sDst As String
        sSrc = ""
        sDst = "c:\test.gif"
        Call URLDownloadToFile(0, sSrc, sDst, 0, 0)
    End Sub


    Author Comment

    Have closed off this question thanks because the next question is a different but is a continuation of the last one. please feel free chris to follow the question all help would be appreciated

    Author Comment

    will test the above last posting

    Author Comment

    well that did it I just have to integrate it with the other code and it will be a goer, pat your self on the back chris very good, when your in sydney I owe you a beer

    Featured Post

    Courses: Start Training Online With Pros, Today

    Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

    Join & Write a Comment

    My experience with Windows 10 over a one year period and suggestions for smooth operation
    Are you using email marketing software? If not, you're missing out on effortless marketing and the reaching of desired conversion rates through email marketing software.
    Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
    This Experts Exchange video Micro Tutorial shows how to tell Microsoft Office that a word is NOT spelled correctly. Microsoft Office has a built-in, main dictionary that is shared by Office apps, including Excel, Outlook, PowerPoint, and Word. When …

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    21 Experts available now in Live!

    Get 1:1 Help Now