toIterable example

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();
    }

    /** * @return void */
    public function ensureValidity()
    {
        if (!$this->headers->has('To') && !$this->headers->has('Cc') && !$this->headers->has('Bcc')) {
            throw new LogicException('An email must have a "To", "Cc", or "Bcc" header.');
        }

        


    /** * Creates a directory recursively. * * @return void * * @throws IOException On any directory creation failure */
    public function mkdir(string|iterable $dirs, int $mode = 0777)
    {
        foreach ($this->toIterable($dirs) as $dir) {
            if (is_dir($dir)) {
                continue;
            }

            if (!self::box('mkdir', $dir$mode, true) && !is_dir($dir)) {
                throw new IOException(sprintf('Failed to create "%s": ', $dir).self::$lastError, 0, null, $dir);
            }
        }
    }

    /** * Checks the existence of files or directories. */
use Symfony\Component\Mime\RawMessage;

class SentMessageTest extends TestCase
{
    public function test()
    {
        $m = new SentMessage($r = new RawMessage('Email')$e = new Envelope(new Address('fabien@example.com')[new Address('helene@example.com')]));
        $this->assertSame($r$m->getOriginalMessage());
        $this->assertSame($r$m->getMessage());
        $this->assertSame($e$m->getEnvelope());
        $this->assertEquals($r->toString()$m->toString());
        $this->assertEquals($r->toIterable()$m->toIterable());

        $m = new SentMessage($r = (new Email())->from('fabien@example.com')->to('helene@example.com')->text('text')$e);
        $this->assertSame($r$m->getOriginalMessage());
        $this->assertNotSame($r$m->getMessage());
    }
}
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();
    }

    /** * @return void */
    public function ensureValidity()
    {
        if (!$this->headers->has('To') && !$this->headers->has('Cc') && !$this->headers->has('Bcc')) {
            throw new LogicException('An email must have a "To", "Cc", or "Bcc" header.');
        }

        

        $string .= '--'.$this->getBoundary()."--\r\n";

        return $string;
    }

    public function bodyToIterable(): iterable
    {
        $parts = $this->getParts();
        foreach ($parts as $part) {
            yield '--'.$this->getBoundary()."\r\n";
            yield from $part->toIterable();
            yield "\r\n";
        }
        yield '--'.$this->getBoundary()."--\r\n";
    }

    public function asDebugString(): string
    {
        $str = parent::asDebugString();
        foreach ($this->getParts() as $part) {
            $lines = explode("\n", $part->asDebugString());
            $str .= "\n └ ".array_shift($lines);
            
/** * Handles cleaning process and returns the number of deleted media objects */
    private function handleCleanup(SymfonyStyle $io): int
    {
        $em = $this->getContainer()->get(ModelManager::class);

        $query = $em->getRepository(Media::class)->getAlbumMediaQuery(Album::ALBUM_GARBAGE);
        $query->setHydrationMode(AbstractQuery::HYDRATE_OBJECT);

        $count = (int) $em->getQueryCount($query);
        $iterableResult = $query->toIterable();

        $progressBar = $io->createProgressBar($count);

        try {
            foreach ($iterableResult as $key => $media) {
                $em->remove($media);
                if ($key % 100 === 0) {
                    $em->flush();
                    $em->clear();
                }
                $progressBar->advance();
            }

        $string .= '--'.$this->getBoundary()."--\r\n";

        return $string;
    }

    public function bodyToIterable(): iterable
    {
        $parts = $this->getParts();
        foreach ($parts as $part) {
            yield '--'.$this->getBoundary()."\r\n";
            yield from $part->toIterable();
            yield "\r\n";
        }
        yield '--'.$this->getBoundary()."--\r\n";
    }

    public function asDebugString(): string
    {
        $str = parent::asDebugString();
        foreach ($this->getParts() as $part) {
            $lines = explode("\n", $part->asDebugString());
            $str .= "\n └ ".array_shift($lines);
            
$this->original = $message;
        $this->envelope = $envelope;

        if ($message instanceof Message) {
            $message = clone $message;
            $headers = $message->getHeaders();
            if (!$headers->has('Message-ID')) {
                $headers->addIdHeader('Message-ID', $message->generateMessageId());
            }
            $this->messageId = $headers->get('Message-ID')->getId();
            $this->raw = new RawMessage($message->toIterable());
        } else {
            $this->raw = $message;
        }
    }

    public function getMessage(): RawMessage
    {
        return $this->raw;
    }

    public function getOriginalMessage(): RawMessage
    {


        try {
            $envelope = $message->getEnvelope();
            $this->doMailFromCommand($envelope->getSender()->getEncodedAddress());
            foreach ($envelope->getRecipients() as $recipient) {
                $this->doRcptToCommand($recipient->getEncodedAddress());
            }

            $this->executeCommand("DATA\r\n", [354]);
            try {
                foreach (AbstractStream::replace("\r\n.", "\r\n..", $message->toIterable()) as $chunk) {
                    $this->stream->write($chunk, false);
                }
                $this->stream->flush();
            } catch (TransportExceptionInterface $e) {
                throw $e;
            } catch (\Exception $e) {
                $this->stream->terminate();
                $this->started = false;
                $this->getLogger()->debug(sprintf('Email transport "%s" stopped', __CLASS__));
                throw $e;
            }
            
use Symfony\Component\Mime\RawMessage;

class RawMessageTest extends TestCase
{
    /** * @dataProvider provideMessages */
    public function testToString($messageParameter)
    {
        $message = new RawMessage($messageParameter);
        $this->assertEquals('some string', $message->toString());
        $this->assertEquals('some string', implode('', iterator_to_array($message->toIterable())));
        // calling methods more than once work         $this->assertEquals('some string', $message->toString());
        $this->assertEquals('some string', implode('', iterator_to_array($message->toIterable())));
    }

    public static function provideMessages(): array
    {
        return [
            'string' => ['some string'],
            'traversable' => [new \ArrayObject(['some', ' ', 'string'])],
            'array' => [['some', ' ', 'string']],
        ];

    public function emptyTrashAction()
    {
        $em = $this->get(ModelManager::class);
        $query = $em->getRepository(Media::class)->getAlbumMediaQuery(Album::ALBUM_GARBAGE);
        $query->setHydrationMode(AbstractQuery::HYDRATE_OBJECT);

        foreach ($query->toIterable() as $key => $media) {
            $em->remove($media);
            if ($key % 100 === 0) {
                $em->flush();
                $em->clear();
            }
        }
        $em->flush();
        $em->clear();

        $this->View()->assign(['success' => true]);
    }

    
$this->certs = $this->normalizeFilePath($certificate);
        }

        $this->cipher = $cipher ?? \OPENSSL_CIPHER_AES_256_CBC;
    }

    public function encrypt(Message $message): Message
    {
        $bufferFile = tmpfile();
        $outputFile = tmpfile();

        $this->iteratorToFile($message->toIterable()$bufferFile);

        if (!@openssl_pkcs7_encrypt(stream_get_meta_data($bufferFile)['uri']stream_get_meta_data($outputFile)['uri']$this->certs, [], 0, $this->cipher)) {
            throw new RuntimeException(sprintf('Failed to encrypt S/Mime message. Error: "%s".', openssl_error_string()));
        }

        $mimePart = $this->convertMessageToSMimePart($outputFile, 'application', 'pkcs7-mime');
        $mimePart->getHeaders()
            ->addTextHeader('Content-Transfer-Encoding', 'base64')
            ->addParameterizedHeader('Content-Disposition', 'attachment', ['name' => 'smime.p7m'])
        ;

        
$expected = <<<EOF From: fabien@symfony.com MIME-Version: 1.0 Date: %s Message-ID: <%s@symfony.com> Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable EOF;
        $this->assertStringMatchesFormat($expectedstr_replace("\r\n", "\n", $message->toString()));
        $this->assertStringMatchesFormat($expectedstr_replace("\r\n", "\n", implode('', iterator_to_array($message->toIterable(), false))));

        $message = new Message(null, new TextPart('content'));
        $message->getHeaders()->addMailboxListHeader('From', ['fabien@symfony.com']);
        $expected = <<<EOF From: fabien@symfony.com MIME-Version: 1.0 Date: %s Message-ID: <%s@symfony.com> Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable content


        $this->signOptions = $signOptions ?? \PKCS7_DETACHED;
        $this->extraCerts = $extraCerts ? realpath($extraCerts) : null;
    }

    public function sign(Message $message): Message
    {
        $bufferFile = tmpfile();
        $outputFile = tmpfile();

        $this->iteratorToFile($message->getBody()->toIterable()$bufferFile);

        if (!@openssl_pkcs7_sign(stream_get_meta_data($bufferFile)['uri']stream_get_meta_data($outputFile)['uri']$this->signCertificate, $this->signPrivateKey, []$this->signOptions, $this->extraCerts)) {
            throw new RuntimeException(sprintf('Failed to sign S/Mime message. Error: "%s".', openssl_error_string()));
        }

        return new Message($message->getHeaders()$this->convertMessageToSMimePart($outputFile, 'multipart', 'signed'));
    }
}
->subject('Testing')
            ->from('noreply@example.com')
            ->text('El Barto was not here');

        $message->getHeaders()->addIdHeader('Message-ID', 'some@id');

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

        $restoredMessage = unserialize(serialize($signedMessage));

        self::assertSame($this->iterableToString($signedMessage->toIterable())$this->iterableToString($restoredMessage->toIterable()));
        self::assertSame($signedMessage->toString()$restoredMessage->toString());

        $this->assertMessageSignatureIsValid($restoredMessage$message);
    }

    public function testSignedMessageWithBcc()
    {
        $message = (new Email())
            ->date(new \DateTimeImmutable('2019-04-07 10:36:30', new \DateTimeZone('Europe/Paris')))
            ->to('fabien@symfony.com')
            ->addBcc('fabien@symfony.com', 's.stok@rollerscapes.net')
            
Home | Imprint | This part of the site doesn't use cookies.