Saturday, January 12, 2013

Downloading attachments with cfimap

<cfimap> is very easy to use but it can become a real pain if you are using ColdFusion at shared hosting, specially when downloading attachments. <cfimap> by default save attachments in temp folder (GetTempDirectory()) but on shared hosting, your host may not give you read/write access to that folder. In such situation, you can use "attachmentpath" attribute of cfimap to define path where cfimap should download the attachments. Unfortunately, this may also not work on shared hosting. Here is a workaround which I use to download attachments.

<!--- Creating a Temp Attachmetn Folder in Memory ---> 
        <cfset sfolder = "ram://attachments" />
        <cfif NOT DirectoryExists(#sfolder#) >
            <cfdirectory
                action="create"
                directory="#sfolder#"
            />       
        </cfif>
    <cfimap
        server = "IMAP SERVER"
        username = "MyUserName"        
        action = "open"
        secure="yes"
        password = "MyPassword"
        connection = "imapEmail"
        timeout="300" generateUniqueFilenames="Yes">   
   
    <cfimap action="GetAll" AttachmentPath ="#sfolder#" connection="imapEmail" name="AllEmails">    


    <cfoutput>
        <!--- Looping directory files --->
            <cfdirectory
                name="files"
                action="list"
                directory="#sfolder#"
            />
            <cfloop query="files">
                <cffile action="copy"
                      destination="C:\inetpub\wwwroot\mydomain.com\wwwroot\attachments"
                      nameconflict="MakeUnique"
                      source="#sfolder#/#files.name#">
                 #files.name# has been downloaded. <br/>    
                <cffile action="delete" file="#sfolder#/#files.name#" />
            </cfloop>
    </cfoutput>

    <cfimap action="close" connection = "imapEmail">

First, we create a folder "attachments" in Memory and then downloaded all attachment in that folder. Later, we loop through all the files in "attachments" directory and copy them to our destination folder. Simple!!

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. what about a mail containing different files with same name files ,eg:if it contain a.gif,a.gif and when i use above code it only downloads first file.

    ReplyDelete