Save an email attachment using Zend Mail
To do some automated billing I needed to grab an email attachment off the exchange server. The Zend framework made it very easy to connect to the mail server and navigate files, and that part of the code came directly from the Zend Framework documentation. The issue that took the longest was saving the attachment. I could not figure out how to decode the attachment using the Zend framework. Let me know if you have a better way or if it helps you out.
NOTE: If you getting the mail from the INBOX you do not have to use the getFolders() function.
// Connecting with Imap
$mail = new Zend_Mail_Storage_Imap(
array('host' => 'SERVER',
'user' => 'USERNAME',
'password' => 'PASSWORD'));
// Navigate to desired folder
$folder = $mail->getFolders()->INBOX->Info;
// Change to folder
$mail->selectFolder($folder);
// Loop through messages
foreach ($mail as $message)
{
// Find desired message subject
if($message->subject == 'SUBJECT')
{
// Check for attachment
if($message->isMultipart())
{
$part = $message->getPart(2);
}
// Get the attacment file name
$fileName = $part->getHeader('content-description');
// Get the attachement and decode
$attachment = base64_decode($part->getContent());
// Save the attachment
$fh = fopen($fileName, 'w');
fwrite($fh, $attachment);
fclose($fh);
}
}





