Question

Can anyone point me in the right direction on how to use php to grab the attachment from an email? I am already using php to successfully process a rather large .csv file and exucute different actions based on conditions. It is working very well, but I have now been asked to automate the action of downloading the email that contains the new .csv file several times a day.

Using this as the start of my code, I am do what I please with the information in the .csv file once I download it, and place it on my server. So can I just open the attachment from the email, and skip the step of downloading it, and placing it on my server?

   $handle = fopen("updateaccounting.csv", "r");
        // loop content of csv file, using comma as delemiter
        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
        $compareid = $data[0];
        $date = $data[1];
        $first = $data[5];
        $last = $data[6];
        $city = $data[7];
        $fundedamount = $data[10];
        $xmlstatus = $data[13];
        $custtestid = substr($compareid, 0, 11);

My question is how to grab the .csv file using php running on a cronjob. This way I can use my existing code that processes the file along with what I am looking for, how to automate the process of getting the file.. Any help would be GREAT! Thank you so much. Jason

Was it helpful?

Solution

For this solution, you will need to access the mailbox using IMAP. Chances are, this is already supported.

Next, you can grab the file attachment into a $data variable (without needing to save it). See this bountied answer: Retrieving file attachment. Then, you should be able to create your csv using your code (which of course you've put into a function now, right? :)) If you have questions on accessing mail via IMAP, search StackOverflow, try it out using examples from PHP Manual and then post any new questions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top