示例#1
0
 /**
  * Process inline images. Convert it to embedded attachments and update message body.
  *
  * @param \Swift_Message $message
  * @param EmailModel     $model
  */
 protected function processEmbeddedImages(\Swift_Message $message, EmailModel $model)
 {
     if ($model->getType() === 'html') {
         $guesser = ExtensionGuesser::getInstance();
         $body = $message->getBody();
         $body = preg_replace_callback('/<img(.*)src(\\s*)=(\\s*)["\'](.*)["\']/U', function ($matches) use($message, $guesser, $model) {
             if (count($matches) === 5) {
                 // 1st match contains any data between '<img' and 'src' parts (e.g. 'width=100')
                 $imgConfig = $matches[1];
                 // 4th match contains src attribute value
                 $srcData = $matches[4];
                 if (strpos($srcData, 'data:image') === 0) {
                     list($mime, $content) = explode(';', $srcData);
                     list($encoding, $file) = explode(',', $content);
                     $mime = str_replace('data:', '', $mime);
                     $fileName = sprintf('%s.%s', uniqid(), $guesser->guess($mime));
                     $swiftAttachment = \Swift_Image::newInstance(ContentDecoder::decode($file, $encoding), $fileName, $mime);
                     /** @var $message \Swift_Message */
                     $id = $message->embed($swiftAttachment);
                     $attachmentContent = new EmailAttachmentContent();
                     $attachmentContent->setContent($file);
                     $attachmentContent->setContentTransferEncoding($encoding);
                     $emailAttachment = new EmailAttachment();
                     $emailAttachment->setEmbeddedContentId($swiftAttachment->getId());
                     $emailAttachment->setFileName($fileName);
                     $emailAttachment->setContentType($mime);
                     $attachmentContent->setEmailAttachment($emailAttachment);
                     $emailAttachment->setContent($attachmentContent);
                     $emailAttachmentModel = new EmailAttachmentModel();
                     $emailAttachmentModel->setEmailAttachment($emailAttachment);
                     $model->addAttachment($emailAttachmentModel);
                     return sprintf('<img%ssrc="%s"', $imgConfig, $id);
                 }
             }
         }, $body);
         $message->setBody($body, 'text/html');
     }
 }