DataPart example


        return $this->htmlCharset;
    }

    /** * @param resource|string $body * * @return $this */
    public function attach($body, string $name = null, string $contentType = null)static
    {
        return $this->addPart(new DataPart($body$name$contentType));
    }

    /** * @return $this */
    public function attachFromPath(string $path, string $name = null, string $contentType = null)static
    {
        return $this->addPart(new DataPart(new File($path)$name$contentType));
    }

    /** * @param resource|string $body * * @return $this */
if (!\count($catalogue->all($domain))) {
                    continue;
                }

                $phraseLocale = $this->getLocale($catalogue->getLocale());

                $content = $this->xliffFileDumper->formatCatalogue($catalogue$domain['default_locale' => $this->defaultLocale]);
                $filename = sprintf('%d-%s-%s.xlf', date('YmdHis')$domain$catalogue->getLocale());

                $this->writeConfig['tags'] = $domain;
                $this->writeConfig['locale_id'] = $phraseLocale;
                $fields = array_merge($this->writeConfig, ['file' => new DataPart($content$filename, 'application/xml')]);

                $formData = new FormDataPart($fields);

                $response = $this->httpClient->request('POST', 'uploads', [
                    'body' => $formData->bodyToIterable(),
                    'headers' => $formData->getPreparedHeaders()->toArray(),
                ]);

                if (201 !== $statusCode = $response->getStatusCode()) {
                    $this->logger->error(sprintf('Unable to upload translations for domain "%s" to phrase: "%s".', $domain$response->getContent(false)));

                    


    public function testToString()
    {
        $p = DataPart::fromPath($file = __DIR__.'/../../Fixtures/mimetypes/test.gif');
        $this->assertEquals(base64_encode(file_get_contents($file))$p->bodyToString());
    }

    public function testContentLineLength()
    {
        $f = new FormDataPart([
            'foo' => new DataPart($foo = str_repeat('foo', 1000), 'foo.txt', 'text/plain'),
            'bar' => $bar = str_repeat('bar', 1000),
        ]);
        $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'),
        ]);
private function uploadMedia(array $media): array
    {
        $responses = [];

        foreach ($media as [
            'file' => $file,
            'thumbnail' => $thumbnail,
            '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', [
                


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

    protected function doSendHttp(SentMessage $message): ResponseInterface
    {
        $body = new FormDataPart([
            'to' => implode(',', $this->stringifyAddresses($message->getEnvelope()->getRecipients())),
            'message' => new DataPart($message->toString(), 'message.mime'),
        ]);
        $headers = [];
        foreach ($body->getPreparedHeaders()->all() as $header) {
            $headers[] = $header->toString();
        }

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

    public function testSendEmailWithAttachmentsShouldCalledInfobipWithTheRightParameters()
    {
        $email = $this->basicValidEmail()
            ->text('foobar')
            ->addPart(new DataPart('some attachment', 'attachment.txt', 'text/plain'))
            ->addPart((new DataPart('some inline attachment', 'inline.txt', 'text/plain'))->asInline())
        ;

        $this->transport->send($email);

        $options = $this->response->getRequestOptions();
        $this->arrayHasKey('body');
        $this->assertStringMatchesFormat(<<<'TXT' %a --%s Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Content-Disposition: form-data; name="text" foobar --%s Content-Type: text/plain Content-Transfer-Encoding: 8bit Content-Disposition: form-data; name="attachment"; filename="attachment.txt" some attachment --%s Content-Type: text/plain Content-Transfer-Encoding: 8bit Content-Disposition: form-data; name="inlineImage"; filename="inline.txt" some inline attachment --%s--
$this->assertStringMatchesFormat($expectedstr_replace("\r\n", "\n", implode('', iterator_to_array($message->toIterable(), false))));
    }

    public function testSymfonySerialize()
    {
        // we don't add from/sender to check that it's not needed to serialize an email         $body = new MixedPart(
            new AlternativePart(
                new TextPart('Text content'),
                new TextPart('HTML content', 'utf-8', 'html')
            ),
            new DataPart('text data', 'text.txt')
        );
        $body->getHeaders()->addHeader('foo', 'bar');
        $e = new Message((new Headers())->addMailboxListHeader('To', ['you@example.com'])$body);
        $expected = clone $e;

        $expectedJson = <<<EOF { "headers": { "to": [ { "addresses": [ { "address": "you@example.com", "name": "" } ], "name": "To", "lineLength": 76, "lang": null, "charset": "utf-8" } ] }, "body": { "boundary": null, "parts": [ { "boundary": null, "parts": [ { "body": "Text content", "charset": "utf-8", "subtype": "plain", "disposition": null, "name": null, "encoding": "quoted-printable",%A "headers": [], "class": "Symfony\\\\Component\\\\Mime\\\\Part\\\TextPart" }, { "body": "HTML content", "charset": "utf-8", "subtype": "html", "disposition": null, "name": null, "encoding": "quoted-printable",%A "headers": [], "class": "Symfony\\\\Component\\\\Mime\\\\Part\\\\TextPart" } ], "headers": [], "class": "Symfony\\\\Component\\\\Mime\\\\Part\\\\Multipart\\\\AlternativePart" }, { "filename": "text.txt", "mediaType": "application",%A "body": "text data", "charset": null, "subtype": "octet-stream", "disposition": "attachment", "name": "text.txt", "encoding": "base64",%A "headers": [], "class": "Symfony\\\\Component\\\\Mime\\\\Part\\\\DataPart" } ], "headers": { "foo": [ { "value": "bar", "name": "foo", "lineLength": 76, "lang": null, "charset": "utf-8" } ] }, "class": "Symfony\\\\Component\\\\Mime\\\\Part\\\\Multipart\\\\MixedPart" }, "message": null }


    public function testSignedMessageWithAttachments()
    {
        $message = new Email((new Headers())
            ->addDateHeader('Date', new \DateTimeImmutable('2019-04-07 10:36:30', new \DateTimeZone('Europe/Paris')))
            ->addMailboxListHeader('From', ['fabien@symfony.com'])
            ->addMailboxListHeader('To', ['fabien@symfony.com'])
        );
        $message->html('html content <img src="cid:test.gif">');
        $message->text('text content');
        $message->addPart(new DataPart(fopen(__DIR__.'/../Fixtures/mimetypes/test', 'r')));
        $message->addPart(new DataPart(fopen(__DIR__.'/../Fixtures/mimetypes/test.gif', 'r'), 'test.gif'));

        $signer = new SMimeSigner($this->samplesDir.'sign.crt', $this->samplesDir.'sign.key');

        $signedMessage = $signer->sign($message);
        $this->assertMessageSignatureIsValid($signedMessage$message);
    }

    public function testSignedMessageExtraCerts()
    {
        $message = new Message(
            (
$method = 'POST';
        $options = [];
        $mediaId ??= $response->toArray()['media_id_string'];
        $pause = 0;

        if (0 <= $seq) {
            $options['query'] = [
                'command' => 'APPEND',
                'media_id' => $mediaId,
                'segment_index' => (string) $seq,
            ];
            $options['body'] = ['media' => new DataPart(fread($h, 1024 * 1024))];
            $seq = feof($h) ? -1 : 1 + $seq;
        } elseif (-1 === $seq) {
            $options['query'] = ['command' => 'FINALIZE', 'media_id' => $mediaId];
            $seq = -2;
        } elseif (-2 !== $seq) {
            return;
        } elseif ('succeeded' === $state = $response->toArray()['processing_info']['state'] ?? 'succeeded') {
            if ($alt) {
                $pool[$i] = $this->request('POST', '/1.1/media/metadata/create.json', [
                    'json' => [
                        'media_id' => $mediaId,
                        


        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];
            }
        }
    }

    /** * @param Address[] $addresses */
return $this;
    }

    /** * @return $this */
    public function exception(\Throwable|FlattenException $exception)static
    {
        $exceptionAsString = $this->getExceptionAsString($exception);

        $this->context['exception'] = true;
        $this->addPart(new DataPart($exceptionAsString, 'exception.txt', 'text/plain'));
        $this->importance(self::IMPORTANCE_URGENT);

        if (!$this->getSubject()) {
            $this->subject($exception->getMessage());
        }

        return $this;
    }

    /** * @return $this */
$transport = new MailerSendApiTransport('ACCESS_KEY', $client);

        $mail = new Email();
        $mail->subject('Test subject')
            ->to(new Address('test_to@example.com', 'Test to name'))
            ->from(new Address('test_from@example.com', 'Test from name'))
            ->addCc('test_cc@example.com')
            ->addBcc('test_bcc@example.com')
            ->addReplyTo('test_reply_to@example.com')
            ->html('<html><body><p>Lorem ipsum.</p><img src="cid:test_cid@symfony"></body></html>')
            ->addPart(new DataPart('content', 'attachment.txt', 'text/plain'))
            ->addPart((new DataPart('inline content', 'inline.txt', 'text/plain'))->asInline()->setContentId('test_cid@symfony'));

        $message = $transport->send($mail);

        $this->assertSame('test_message_id', $message->getMessageId());
    }

    public function testSendThrowsForErrorResponse()
    {
        $client = new MockHttpClient(function Dstring $method, string $url, array $options): ResponseInterface {
            return new MockResponse(json_encode(['message' => 'i\'m a teapot'])[
                
$mailer = new SendgridApiTransport('foo', $httpClient);
        $mailer->send($email);
    }

    public function testLineBreaksInEncodedAttachment()
    {
        $email = new Email();
        $email->from('foo@example.com')
            ->to('bar@example.com')
            // even if content doesn't include new lines, the base64 encoding performed later may add them             ->addPart(new DataPart('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod', 'lorem.txt'));

        $response = $this->createMock(ResponseInterface::class);

        $response
            ->expects($this->once())
            ->method('getStatusCode')
            ->willReturn(202);
        $response
            ->expects($this->once())
            ->method('getHeaders')
            ->willReturn(['x-message-id' => '1']);

        

        return $this->htmlCharset;
    }

    /** * @param resource|string $body * * @return $this */
    public function attach($body, string $name = null, string $contentType = null)static
    {
        return $this->addPart(new DataPart($body$name$contentType));
    }

    /** * @return $this */
    public function attachFromPath(string $path, string $name = null, string $contentType = null)static
    {
        return $this->addPart(new DataPart(new File($path)$name$contentType));
    }

    /** * @param resource|string $body * * @return $this */
public function testSendInvalidMessage()
    {
        $stream = new DummyStream();

        $transport = new SmtpTransport($stream);
        $transport->setPingThreshold(1);

        $message = new Email();
        $message->to('recipient@example.org');
        $message->from('sender@example.org');
        $message->addPart(new DataPart(new File('/does_not_exists')));

        try {
            $transport->send($message);
            $this->fail('Expected Symfony\Component\Mime\Exception\InvalidArgumentException to be thrown');
        } catch (InvalidArgumentException $e) {
            $this->assertMatchesRegularExpression('{Path "/does_not_exists"}i', $e->getMessage());
        }

        $this->assertNotContains("\r\n.\r\n", $stream->getCommands());
        $this->assertTrue($stream->isClosed());
    }

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