getAttachments example

    // (Note this is copied verbatim from     // \Drupal\Core\Render\HtmlResponseAttachmentsProcessor::processAttachments)     try {
      $response = $this->renderPlaceholders($response);
    }
    catch (EnforcedResponseException $e) {
      return $e->getResponse();
    }

    // Extract BigPipe placeholders; HtmlResponseAttachmentsProcessor does not     // know (nor need to know) how to process those.     $attachments = $response->getAttachments();
    $big_pipe_placeholders = [];
    $big_pipe_nojs_placeholders = [];
    if (isset($attachments['big_pipe_placeholders'])) {
      $big_pipe_placeholders = $attachments['big_pipe_placeholders'];
      unset($attachments['big_pipe_placeholders']);
    }
    if (isset($attachments['big_pipe_nojs_placeholders'])) {
      $big_pipe_nojs_placeholders = $attachments['big_pipe_nojs_placeholders'];
      unset($attachments['big_pipe_nojs_placeholders']);
    }
    $html_response = clone $response;
    
foreach ($email->getHeaders()->all() as $header) {
            if ($convertConf = self::HEADER_TO_MESSAGE[$header->getName()] ?? false) {
                $fields[$convertConf] = $header->getBodyAsString();
            }
        }

        return new FormDataPart($fields);
    }

    private function attachmentsFormData(array &$message, Email $email): void
    {
        foreach ($email->getAttachments() as $attachment) {
            $headers = $attachment->getPreparedHeaders();
            $filename = $headers->getHeaderParameter('Content-Disposition', 'filename');

            $dataPart = new DataPart($attachment->getBody()$filename$attachment->getMediaType().'/'.$attachment->getMediaSubtype());

            if ('inline' === $headers->getHeaderBody('Content-Disposition')) {
                $message[] = ['inlineImage' => $dataPart];
            } else {
                $message[] = ['attachment' => $dataPart];
            }
        }
    }


    public function testAttachments()
    {
        // inline part         $contents = file_get_contents($name = __DIR__.'/Fixtures/mimetypes/test', 'r');
        $att = new DataPart($file = fopen($name, 'r'), 'test');
        $inline = (new DataPart($contents, 'test'))->asInline();
        $e = new Email();
        $e->addPart(new DataPart($file, 'test'));
        $e->addPart((new DataPart($contents, 'test'))->asInline());
        $this->assertEquals([$att$inline]$e->getAttachments());

        // inline part from path         $att = DataPart::fromPath($name, 'test');
        $inline = DataPart::fromPath($name, 'test')->asInline();
        $e = new Email();
        $e->addPart(new DataPart(new File($name)));
        $e->addPart((new DataPart(new File($name)))->asInline());
        $this->assertEquals([$att->bodyToString()$inline->bodyToString()]array_map(fn (DataPart $a) => $a->bodyToString()$e->getAttachments()));
        $this->assertEquals([$att->getPreparedHeaders()$inline->getPreparedHeaders()]array_map(fn (DataPart $a) => $a->getPreparedHeaders()$e->getAttachments()));
    }

    

  public function onRespondEarly(ResponseEvent $event) {
    $response = $event->getResponse();
    if (!$response instanceof HtmlResponse) {
      return;
    }

    // Wrap the scripts_bottom placeholder with a marker before and after,     // because \Drupal\big_pipe\Render\BigPipe needs to be able to extract that     // markup if there are no-JS BigPipe placeholders.     // @see \Drupal\big_pipe\Render\BigPipe::sendPreBody()     $attachments = $response->getAttachments();
    if (isset($attachments['html_response_attachment_placeholders']['scripts_bottom'])) {
      $scripts_bottom_placeholder = $attachments['html_response_attachment_placeholders']['scripts_bottom'];
      $content = $response->getContent();
      $content = str_replace($scripts_bottom_placeholder, '<drupal-big-pipe-scripts-bottom-marker>' . $scripts_bottom_placeholder . '<drupal-big-pipe-scripts-bottom-marker>', $content);
      $response->setContent($content);
    }
  }

  /** * Transforms a HtmlResponse to a BigPipeResponse. * * @param \Symfony\Component\HttpKernel\Event\ResponseEvent $event * The event to process. */

        if ($headersAndTags = $this->prepareHeadersAndTags($email->getHeaders())) {
            $payload = array_merge($payload$headersAndTags);
        }

        return $payload;
    }

    private function prepareAttachments(Email $email): array
    {
        $attachments = [];
        foreach ($email->getAttachments() as $attachment) {
            $headers = $attachment->getPreparedHeaders();
            $filename = $headers->getHeaderParameter('Content-Disposition', 'filename');

            $att = [
                'content' => str_replace("\r\n", '', $attachment->bodyToString()),
                'name' => $filename,
            ];

            $attachments[] = $att;
        }

        

  public static function createFromObject($object) {
    $meta = parent::createFromObject($object);

    if ($object instanceof AttachmentsInterface) {
      $meta->attachments = $object->getAttachments();
    }

    return $meta;
  }

  /** * {@inheritdoc} */
  public function addCacheableDependency($other_object) {
    parent::addCacheableDependency($other_object);

    
'name' => $address->getName(),
            ];
        }

        return $recipients;
    }

    private function prepareAttachments(Email $email): array
    {
        $attachments = [];

        foreach ($email->getAttachments() as $attachment) {
            $headers = $attachment->getPreparedHeaders();
            $filename = $headers->getHeaderParameter('Content-Disposition', 'filename');

            $att = [
                'content' => base64_encode($attachment->getBody()),
                'filename' => $filename,
            ];

            if ('inline' === $headers->getHeaderBody('Content-Disposition')) {
                $att['disposition'] = 'inline';
                $att['id'] = $attachment->getContentId();
            }
private function formatAddress(Address $address): array
    {
        return [
            'Email' => $address->getAddress(),
            'Name' => $address->getName(),
        ];
    }

    private function prepareAttachments(Email $email, ?string $html): array
    {
        $attachments = $inlines = [];
        foreach ($email->getAttachments() as $attachment) {
            $headers = $attachment->getPreparedHeaders();
            $filename = $headers->getHeaderParameter('Content-Disposition', 'filename');
            $formattedAttachment = [
                'ContentType' => $attachment->getMediaType().'/'.$attachment->getMediaSubtype(),
                'Filename' => $filename,
                'Base64Content' => $attachment->bodyToString(),
            ];
            if ('inline' === $headers->getHeaderBody('Content-Disposition')) {
                $formattedAttachment['ContentID'] = $headers->getHeaderParameter('Content-Disposition', 'name');
                $inlines[] = $formattedAttachment;
            } else {
                
/** @var \Drupal\Core\Render\BubbleableMetadata $early_rendering_bubbleable_metadata */
      $early_rendering_bubbleable_metadata = $context->pop();

      // If a render array or AjaxResponse is returned by the controller, merge       // the "lost" bubbleable metadata.       if (is_array($response)) {
        BubbleableMetadata::createFromRenderArray($response)
          ->merge($early_rendering_bubbleable_metadata)
          ->applyTo($response);
      }
      elseif ($response instanceof AjaxResponse) {
        $response->addAttachments($early_rendering_bubbleable_metadata->getAttachments());
        // @todo Make AjaxResponse cacheable in         // https://www.drupal.org/node/956186. Meanwhile, allow contrib         // subclasses to be.         if ($response instanceof CacheableResponseInterface) {
          $response->addCacheableDependency($early_rendering_bubbleable_metadata);
        }
      }
      // If a non-Ajax Response or domain object is returned and it cares about       // attachments or cacheability, then throw an exception: early rendering       // is not permitted in that case. It is the developer's responsibility       // to not use early rendering.


            $fileAttachment = $mail->createAttachment(
                $this->filesystem->read($filePath)
            );
            $fileAttachment->filename = $fileName;
        }
    }

    protected function assignTemplateDocuments(Log $logEntry, Enlight_Components_Mail $mail): void
    {
        if ($logEntry->getType() === null || empty($logEntry->getType()->getAttachments())) {
            return;
        }

        $entryShopId = $logEntry->getShop() ? $logEntry->getShop()->getId() : null;
        $attachments = $logEntry->getType()->getAttachments();

        foreach ($attachments as $attachment) {
            $attachmentShopId = $attachment->getShopId();

            if ($attachmentShopId !== null && $attachmentShopId !== $entryShopId) {
                continue;
            }


            $payload[$headerName] = $header->getBodyAsString();
        }

        return $payload;
    }

    private function prepareAttachments(Email $email, ?string $html): array
    {
        $attachments = $inlines = [];
        foreach ($email->getAttachments() as $attachment) {
            $headers = $attachment->getPreparedHeaders();
            if ('inline' === $headers->getHeaderBody('Content-Disposition')) {
                // replace the cid with just a file name (the only supported way by Mailgun)                 if ($html) {
                    $filename = $headers->getHeaderParameter('Content-Disposition', 'filename');
                    $new = basename($filename);
                    $html = str_replace('cid:'.$filename, 'cid:'.$new$html);
                    $p = new \ReflectionProperty($attachment, 'filename');
                    $p->setValue($attachment$new);
                }
                $inlines[] = $attachment;
            }


    /** * @param RawMessage $message */
    protected function matches($message): bool
    {
        if (RawMessage::class === $message::class || Message::class === $message::class) {
            throw new \LogicException('Unable to test a message attachment on a RawMessage or Message instance.');
        }

        return $this->expectedValue === \count($message->getAttachments());
    }

    /** * @param RawMessage $message */
    protected function failureDescription($message): string
    {
        return 'the Email '.$this->toString();
    }
}
 elseif (!empty($fromMail)) {
            $mail->setFrom($fromMail);
        }

        $bodyText = $stringCompiler->compileString($mailModel->getContent());
        $mail->setBodyText($bodyText);

        if ($mailModel->isHtml()) {
            $mail->setBodyHtml($stringCompiler->compileString($mailModel->getContentHtml()));
        }

        foreach ($mailModel->getAttachments() as $attachment) {
            if ($attachment->getShopId() !== null
                && ($this->getShop() === null || $attachment->getShopId() !== $this->getShop()->getId())) {
                continue;
            }

            $mediaService = Shopware()->Container()->get(MediaServiceInterface::class);
            if (!$mediaService->has($attachment->getPath())) {
                Shopware()->Container()->get('corelogger')->error('Could not load file: ' . $attachment->getPath());
            } else {
                $fileAttachment = $mail->createAttachment($mediaService->read($attachment->getPath()));
                $fileAttachment->filename = $attachment->getFileName();
            }
    // Drupal 8. In order to resolve this issue properly it is necessary to     // completely separate form submission from rendering.     // @see https://www.drupal.org/node/2367555     try {
      $response = $this->renderPlaceholders($response);
    }
    catch (EnforcedResponseException $e) {
      return $e->getResponse();
    }

    // Get a reference to the attachments.     $attached = $response->getAttachments();

    // Send a message back if the render array has unsupported #attached types.     $unsupported_types = array_diff(
      array_keys($attached),
      ['html_head', 'feed', 'html_head_link', 'http_header', 'library', 'html_response_attachment_placeholders', 'placeholders', 'drupalSettings']
    );
    if (!empty($unsupported_types)) {
      throw new \LogicException(sprintf('You are not allowed to use %s in #attached.', implode(', ', $unsupported_types)));
    }

    // If we don't have any placeholders, there is no need to proceed.
'text' => $email->getTextBody(),
                'subject' => $email->getSubject(),
                'from_email' => $envelope->getSender()->getAddress(),
                'to' => $this->getRecipientsPayload($email$envelope),
            ],
        ];

        if ('' !== $envelope->getSender()->getName()) {
            $payload['message']['from_name'] = $envelope->getSender()->getName();
        }

        foreach ($email->getAttachments() as $attachment) {
            $headers = $attachment->getPreparedHeaders();
            $disposition = $headers->getHeaderBody('Content-Disposition');

            $att = [
                'content' => $attachment->bodyToString(),
                'type' => $headers->get('Content-Type')->getBody(),
            ];

            if ($name = $headers->getHeaderParameter('Content-Disposition', 'name')) {
                $att['name'] = $name;
            }

            
Home | Imprint | This part of the site doesn't use cookies.