getPreparedHeaders example

public function testTheme()
    {
        $email = (new NotificationEmail())->theme('mine');
        $this->assertSame('@email/mine/notification/body.html.twig', $email->getHtmlTemplate());
        $this->assertSame('@email/mine/notification/body.txt.twig', $email->getTextTemplate());
    }

    public function testSubject()
    {
        $email = (new NotificationEmail())->from('me@example.com')->subject('Foo');
        $headers = $email->getPreparedHeaders();
        $this->assertSame('[LOW] Foo', $headers->get('Subject')->getValue());
    }

    public function testPublicMail()
    {
        $email = NotificationEmail::asPublicEmail()
            ->markdown('Foo')
            ->action('Bar', 'http://example.com/')
            ->context(['a' => 'b'])
        ;

        

        $this->expectException(\TypeError::class);
        new TextPart(new \stdClass());
    }

    public function testHeaders()
    {
        $p = new TextPart('content');
        $this->assertEquals(new Headers(
            new ParameterizedHeader('Content-Type', 'text/plain', ['charset' => 'utf-8']),
            new UnstructuredHeader('Content-Transfer-Encoding', 'quoted-printable')
        )$p->getPreparedHeaders());

        $p = new TextPart('content', 'iso-8859-1');
        $this->assertEquals(new Headers(
            new ParameterizedHeader('Content-Type', 'text/plain', ['charset' => 'iso-8859-1']),
            new UnstructuredHeader('Content-Transfer-Encoding', 'quoted-printable')
        )$p->getPreparedHeaders());
    }

    public function testEncoding()
    {
        $p = new TextPart('content', 'utf-8', 'plain', 'base64');
        
throw new \LogicException(sprintf('You cannot use "%s" as the HttpClient component is not installed. Try running "composer require symfony/http-client".', __CLASS__));
        }

        $this->client = $client ?? HttpClient::create();
    }

    public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
    {
        $headers = $this->getHeaders($request);
        $body = '';
        if (null !== $part = $this->getBody($request)) {
            $headers = array_merge($headers$part->getPreparedHeaders()->toArray());
            $body = $part->bodyToIterable();
        }
        $response = $this->client->request($request->getMethod()$request->getUri()[
            'headers' => $headers,
            'body' => $body,
        ] + $request->attributes->get('http_client_options', []));

        $response = new Response($response->getContent(!$catch)$response->getStatusCode()$response->getHeaders(!$catch));

        $response->headers->remove('X-Body-File');
        $response->headers->remove('X-Body-Eval');
        


    public function markAsRendered(): void
    {
        parent::markAsRendered();

        $this->rendered = true;
    }

    public function getPreparedHeaders(): Headers
    {
        $headers = parent::getPreparedHeaders();

        $importance = $this->context['importance'] ?? self::IMPORTANCE_LOW;
        $this->priority($this->determinePriority($importance));
        if ($this->context['importance']) {
            $headers->setHeaderBody('Text', 'Subject', sprintf('[%s] %s', strtoupper($importance)$this->getSubject()));
        }

        return $headers;
    }

    private function determinePriority(string $importance): int
    {
public function request(string $method, string $url, array $options): ResponseInterface
    {
        $url = 'https://'.str_replace('api.', str_starts_with($url, '/1.1/media/') ? 'upload.' : 'api.', $this->getEndpoint()).$url;

        foreach (\is_array($options['body'] ?? null) ? $options['body'] : [] as $v) {
            if (!$v instanceof DataPart) {
                continue;
            }

            $formDataPart = new FormDataPart($options['body']);

            foreach ($formDataPart->getPreparedHeaders()->all() as $header) {
                $options['headers'][] = $header->toString();
            }

            $options['body'] = $formDataPart->bodyToIterable();

            break;
        }

        $oauth = [
            'oauth_consumer_key' => $this->apiKey,
            'oauth_nonce' => self::$nonce = hash('xxh128', self::$nonce ??= random_bytes(16)),
            

        $parts = $f->getParts();
        $this->assertEquals($foo$parts[0]->bodyToString());
        $this->assertEquals($bar$parts[1]->bodyToString());
    }

    public function testBoundaryContentTypeHeader()
    {
        $f = new FormDataPart([
            'file' => new DataPart('data.csv', 'data.csv', 'text/csv'),
        ]);
        $headers = $f->getPreparedHeaders()->toArray();
        $this->assertMatchesRegularExpression(
            '/^Content-Type: multipart\/form-data; boundary=[a-zA-Z0-9\-_]{8}$/',
            $headers[0]
        );
    }
}
self::assertStringNotContainsString('Bcc: ', $messageString, '', true);

        if (!$originalMessage instanceof Message) {
            return;
        }

        if ($originalMessage->getHeaders()->has('Bcc')) {
            self::assertEquals($originalMessage->getHeaders()->get('Bcc')$message->getHeaders()->get('Bcc'));
        }

        if ($originalMessage->getHeaders()->has('Subject')) {
            self::assertEquals($originalMessage->getHeaders()->get('Subject')$message->getPreparedHeaders()->get('Subject'));
            self::assertStringContainsString('Subject:', $messageString, '', true);
        }
    }
}
throw new \LogicException(sprintf('You cannot use "%s" as the HttpClient component is not installed. Try running "composer require symfony/http-client".', __CLASS__));
        }

        $this->client = $client ?? HttpClient::create();
    }

    public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
    {
        $headers = $this->getHeaders($request);
        $body = '';
        if (null !== $part = $this->getBody($request)) {
            $headers = array_merge($headers$part->getPreparedHeaders()->toArray());
            $body = $part->bodyToIterable();
        }
        $response = $this->client->request($request->getMethod()$request->getUri()[
            'headers' => $headers,
            'body' => $body,
        ] + $request->attributes->get('http_client_options', []));

        $response = new Response($response->getContent(!$catch)$response->getStatusCode()$response->getHeaders(!$catch));

        $response->headers->remove('X-Body-File');
        $response->headers->remove('X-Body-Eval');
        
'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;
            }

            
        $headers->remove('Bcc');

        return $headers;
    }

    public function toString(): string
    {
        if (null === $body = $this->getBody()) {
            $body = new TextPart('');
        }

        return $this->getPreparedHeaders()->toString().$body->toString();
    }

    public function toIterable(): iterable
    {
        if (null === $body = $this->getBody()) {
            $body = new TextPart('');
        }

        yield $this->getPreparedHeaders()->toString();
        yield from $body->toIterable();
    }

    
if ($attachements = $this->prepareAttachments($email)) {
            $payload['attachment'] = $attachements;
        }

        return $payload;
    }

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

            $attachments[] = [
                'name' => $filename,
                'type' => $headers->get('Content-Type')->getBody(),
                'content' => base64_encode($attachment->bodyToString()),
            ];
        }

        return $attachments;
    }

    


    public function __toString(): string
    {
        return sprintf('mailgun+api://%s?domain=%s', $this->getEndpoint()$this->domain);
    }

    protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $envelope): ResponseInterface
    {
        $body = new FormDataPart($this->getPayload($email$envelope));
        $headers = [];
        foreach ($body->getPreparedHeaders()->all() as $header) {
            $headers[] = $header->toString();
        }

        $endpoint = sprintf('%s/v3/%s/messages', $this->getEndpoint()urlencode($this->domain));
        $response = $this->client->request('POST', 'https://'.$endpoint[
            'auth_basic' => 'api:'.$this->key,
            'headers' => $headers,
            'body' => $body->bodyToIterable(),
        ]);

        try {
            
'Value' => $header->getBodyAsString(),
            ];
        }

        return $payload;
    }

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

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

            if ('inline' === $disposition) {
                $att['cid'] = 'cid:'.$filename;
            }
'description' => $description,
            'focus' => $focus,
        ]) {
            $formDataPart = new FormDataPart(array_filter([
                'file' => new DataPart($file),
                'thumbnail' => $thumbnail ? new DataPart($thumbnail) : null,
                'description' => $description,
                'focus' => $focus,
            ]));

            $headers = [];
            foreach ($formDataPart->getPreparedHeaders()->all() as $header) {
                $headers[] = $header->toString();
            }

            $responses[] = $this->request('POST', '/api/v2/media', [
                'headers' => $headers,
                'body' => $formDataPart->bodyToIterable(),
            ]);
        }

        $mediaIds = [];

        


            return self::addParts($email, \array_slice($parts, 1));
        }

        throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($message)));
    }

    private static function createEmailFromTextPart(Message $message, TextPart $part): Email
    {
        if ('text' === $part->getMediaType() && 'plain' === $part->getMediaSubtype()) {
            return (new Email(clone $message->getHeaders()))->text($part->getBody()$part->getPreparedHeaders()->getHeaderParameter('Content-Type', 'charset') ?: 'utf-8');
        }
        if ('text' === $part->getMediaType() && 'html' === $part->getMediaSubtype()) {
            return (new Email(clone $message->getHeaders()))->html($part->getBody()$part->getPreparedHeaders()->getHeaderParameter('Content-Type', 'charset') ?: 'utf-8');
        }

        throw new RuntimeException(sprintf('Unable to create an Email from an instance of "%s" as the body is too complex.', get_debug_type($message)));
    }

    private static function createEmailFromAlternativePart(Message $message, AlternativePart $part): Email
    {
        $parts = $part->getParts();
        
Home | Imprint | This part of the site doesn't use cookies.