How to save image attachment from email using IMAP & PHP?

st4ck0v3rfl0w picture st4ck0v3rfl0w · Feb 18, 2010 · Viewed 8.6k times · Source

I've successfully written script that connects to my mail server and retrieves the headers and bodies of all new messages. I want to take it one step further to detect if attachment exists (images only), if so, download to server.

How to go about this using PHP & IMAP?

Thanks in advance

Answer

María Antignolo picture María Antignolo · Feb 3, 2020

KimNyholm published an imap client set of methods that enclose the goals you ask: https://github.com/KimNyholm/ubuntu-web-development/blob/master/php/imapClient.php

He wrote this code because of the lack of full tutorials and code examples to process php imap messages, as he explains here: http://kimnyholm.com/a-simple-imap-mail-reader-client/ and based some of his code in drupal libraries.

I enclose an extract of the methods that perform the steps you menction, I hope it solves the question even though I see it's not exactly recent:

Check for attachments and images amongst them:

// ATTACHMENT
  // Any part with a filename is an attachment,
  // so an attached text file (type 0) is not mistaken as the message.
  if(isset($parameter['filename']) || isset($parameter['name'])) {
    $filename = ($parameter['filename'])? $parameter['filename'] : $parameter['name'];
    $filename=iconv_mime_decode($filename, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
    $id = isset($part->id) ? $part->id : '' ;
    $attachments[] = array('inline' => false, 'filename' => $filename, 'part' => $partNo, 'data' => $data, 'id' => $id);
  }
  if ($type==TYPEIMAGE){
    $info=fetchImageInfo($mailbox, $emailNumber, $partNo);
    $attachments[] = array('inline' => true, 'filename' => $info['filename'], 'part' => $partNo, 'data' => $data, 'id' => $info['id']);
  }

Here he saves the data to a tempdir and download it:

function EmailAttachmentsSave(&$mail){
  $html = '';
  $attachments=$mail->attachments;
  $msgNo=trim($mail->headerInfo->Msgno);
  foreach ($attachments as $attachment) {
    $partNo=$attachment['part'];
    $tmpDir= "imapClient/$msgNo/$partNo";
    $dirExists= is_dir($tmpDir);
    if (!$dirExists){
      $dirExists= mkdir($tmpDir, 0777, true) ;
    }
    $fileName=$attachment['filename'];
    $tmpName = "$tmpDir/$fileName";
    $saved = $dirExists && file_put_contents($tmpName, $attachment['data']);
    $tmpName=htmlentities($tmpName);
    $fileName=htmlentities($fileName);
    if (!$attachment['inline']){
      $html .= '<span><a href="' . $tmpName . '">' . $fileName . '</a> </span>';
    }
    $cid =$attachment['id'];
    if (isset($cid)){
      $mail->htmlText=EmailEmbeddedLinkReplace($mail->htmlText,$cid,$tmpName);
    }
  }
  return $html ;
}

function EmailPrint($mail){
  $headerInfo=$mail->headerInfo;
  $html = '<h4>' . htmlentities($headerInfo->subject) . '</h4>';
  $html .= '<p>From: ' . htmlentities($headerInfo->fromaddress) . '</p>';
  $html .= '<p>To: ' . htmlentities($headerInfo->toaddress) . '</p>';
  $html .= '<div style="background: lightgrey">' . (empty($mail->htmlText) ? ('<p>' . $mail->plainText . '</p>') : $mail->htmlText) . '</div>';
  return $html ;
}

function EmailDownload($host, $user, $password){
  $html = '<head> <meta charset="UTF-8"> </head>';
  $html .= '<h3>Simple imap client</h3>';
  $mails=EmailGetMany($host, $user, $password);
  $count=count($mails);
  $html .= "<p>$user has $count mails at $host.</p>";
  foreach ($mails as $mail){
      $html .= '<hr>';
      $html .= EmailAttachmentsSave($mail);
      $html .= EmailPrint($mail);
  }
  return $html ;
}