getEnvelope example

parent::__construct($client$dispatcher$logger);
    }

    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,
            
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
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());
    }
}
// avoid success message if nothing was processed         if (1 <= $count) {
            $io->success('All failed messages have been handled or removed!');
        }
    }

    private function runWorker(string $failureTransportName, ReceiverInterface $receiver, SymfonyStyle $io, bool $shouldForce): int
    {
        $count = 0;
        $listener = function DWorkerMessageReceivedEvent $messageReceivedEvent) use ($io$receiver$shouldForce, &$count) {
            ++$count;
            $envelope = $messageReceivedEvent->getEnvelope();

            $this->displaySingleMessage($envelope$io);

            if ($envelope->last(MessageDecodingFailedStamp::class)) {
                throw new \RuntimeException(sprintf('The message with id "%s" could not decoded, it can only be shown or removed.', $this->getMessageId($envelope) ?? '?'));
            }

            $shouldHandle = $shouldForce || 'retry' === $io->choice('Please select an action', ['retry', 'delete'], 'retry');

            if ($shouldHandle) {
                return;
            }
$this->logger = $logger;
        $this->eventDispatcher = $eventDispatcher;
        $this->historySize = $historySize;
    }

    /** * @return void */
    public function onMessageFailed(WorkerMessageFailedEvent $event)
    {
        $retryStrategy = $this->getRetryStrategyForTransport($event->getReceiverName());
        $envelope = $event->getEnvelope();
        $throwable = $event->getThrowable();

        $message = $envelope->getMessage();
        $context = [
            'class' => $message::class,
        ];

        $shouldRetry = $retryStrategy && $this->shouldRetry($throwable$envelope$retryStrategy);

        $retryCount = RedeliveryStamp::getRetryCountFromEnvelope($envelope);
        if ($shouldRetry) {
            

    abstract protected function doSendApi(SentMessage $sentMessage, Email $email, Envelope $envelope): ResponseInterface;

    protected function doSendHttp(SentMessage $message): ResponseInterface
    {
        try {
            $email = MessageConverter::toEmail($message->getOriginalMessage());
        } catch (\Exception $e) {
            throw new RuntimeException(sprintf('Unable to send message with the "%s" transport: ', __CLASS__).$e->getMessage(), 0, $e);
        }

        return $this->doSendApi($message$email$message->getEnvelope());
    }

    /** * @return Address[] */
    protected function getRecipients(Email $email, Envelope $envelope): array
    {
        return array_filter($envelope->getRecipients()fn (Address $address) => false === \in_array($addressarray_merge($email->getCc()$email->getBcc()), true));
    }
}
$exception = new HttpTransportException(sprintf('Unable to send an email: %s (code %s).', $e->getAwsMessage() ?: $e->getMessage()$e->getAwsCode() ?: $e->getCode())$e->getResponse()$e->getCode()$e);
            $exception->appendDebug($e->getResponse()->getInfo('debug') ?? '');

            throw $exception;
        }
    }

    protected function getRequest(SentMessage $message): SendEmailRequest
    {
        $request = [
            'Destination' => new Destination([
                'ToAddresses' => $this->stringifyAddresses($message->getEnvelope()->getRecipients()),
            ]),
            'Content' => [
                'Raw' => [
                    'Data' => $message->toString(),
                ],
            ],
        ];

        if (($message->getOriginalMessage() instanceof Message)
            && $configurationSetHeader = $message->getOriginalMessage()->getHeaders()->get('X-SES-CONFIGURATION-SET')) {
            $request['ConfigurationSetName'] = $configurationSetHeader->getBodyAsString();
        }
namespace Symfony\Component\Messenger\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
use Symfony\Component\Messenger\Stamp\ErrorDetailsStamp;

final class AddErrorDetailsStampListener implements EventSubscriberInterface
{
    public function onMessageFailed(WorkerMessageFailedEvent $event): void
    {
        $stamp = ErrorDetailsStamp::create($event->getThrowable());
        $previousStamp = $event->getEnvelope()->last(ErrorDetailsStamp::class);

        // Do not append duplicate information         if (null === $previousStamp || !$previousStamp->equals($stamp)) {
            $event->addStamps($stamp);
        }
    }

    public static function getSubscribedEvents(): array
    {
        return [
            // must have higher priority than SendFailedMessageForRetryListener
class MessageHandler
{
    private TransportInterface $transport;

    public function __construct(TransportInterface $transport)
    {
        $this->transport = $transport;
    }

    public function __invoke(SendEmailMessage $message): ?SentMessage
    {
        return $this->transport->send($message->getMessage()$message->getEnvelope());
    }
}
throw $exception;
        }

        // "Root dispatch" call is finished, dispatch stored messages.         $exceptions = [];
        while (null !== $queueItem = array_shift($this->queue)) {
            // Save how many messages are left in queue before handling the message             $queueLengthBefore = \count($this->queue);
            try {
                // Execute the stored messages                 $queueItem->getStack()->next()->handle($queueItem->getEnvelope()$queueItem->getStack());
            } catch (\Exception $exception) {
                // Gather all exceptions                 $exceptions[] = $exception;
                // Restore queue to previous state                 $this->queue = \array_slice($this->queue, 0, $queueLengthBefore);
            }
        }

        $this->isRootDispatchCallRunning = false;
        if (\count($exceptions) > 0) {
            throw new DelayedMessageHandlingException($exceptions);
        }


        if (null !== $this->envelope) {
            $message->envelope($this->envelope);
        }

        if (null !== $transportName) {
            $message->transport($transportName);
        }

        if (null === $this->bus) {
            $this->transport->send($message->getMessage()$message->getEnvelope());
        } else {
            $this->bus->dispatch(new SendEmailMessage($message->getMessage()$message->getEnvelope()));
        }
    }

    public function supports(Notification $notification, RecipientInterface $recipient): bool
    {
        return $recipient instanceof EmailRecipientInterface;
    }
}
WorkerMessageHandledEvent::class => 'onMessageHandled',
            SendMessageToTransportsEvent::class => ['onMessageSent', 99],
        ];
    }

    public function onMessageFailed(WorkerMessageFailedEvent $event): void
    {
        if ($event->willRetry()) {
            return;
        }

        $this->handle($event->getEnvelope(), false);
    }

    public function onMessageHandled(WorkerMessageHandledEvent $event): void
    {
        $this->handle($event->getEnvelope(), false);
    }

    public function onMessageSent(SendMessageToTransportsEvent $event): void
    {
        $this->handle($event->getEnvelope(), true);
    }

    

    public function onMessageFailed(WorkerMessageFailedEvent $event)
    {
        if ($event->willRetry()) {
            return;
        }

        $throwable = $event->getThrowable();
        if ($throwable instanceof HandlerFailedException) {
            $throwable = $throwable->getNestedExceptions()[0];
        }
        $envelope = $event->getEnvelope();
        $notification = Notification::fromThrowable($throwable)->importance(Notification::IMPORTANCE_HIGH);
        $notification->subject(sprintf('A "%s" message has just failed: %s.', $envelope->getMessage()::class$notification->getSubject()));

        $this->notifier->send($notification, ...$this->notifier->getAdminRecipients());
    }

    public static function getSubscribedEvents(): array
    {
        return [
            WorkerMessageFailedEvent::class => 'onMessageFailed',
        ];
    }

        if ($event->willRetry()) {
            return;
        }

        if (!$this->failureSenders->has($event->getReceiverName())) {
            return;
        }

        $failureSender = $this->failureSenders->get($event->getReceiverName());

        $envelope = $event->getEnvelope();

        // avoid re-sending to the failed sender         if (null !== $envelope->last(SentToFailureTransportStamp::class)) {
            return;
        }

        $envelope = $envelope->with(
            new SentToFailureTransportStamp($event->getReceiverName()),
            new DelayStamp(0),
            new RedeliveryStamp(0)
        );

        
protected function doSend(SentMessage $message): void
    {
        if (microtime(true) - $this->lastMessageTime > $this->pingThreshold) {
            $this->ping();
        }

        if (!$this->started) {
            $this->start();
        }

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

        $message = new DummyMessage('Hey');
        $envelope = new Envelope($message);

        $middleware = new HandleMessageMiddleware(new HandlersLocator([
            DummyMessage::class => $handlers,
        ]));

        try {
            $envelope = $middleware->handle($envelope$this->getStackMock($nextIsCalled));
        } catch (HandlerFailedException $e) {
            $envelope = $e->getEnvelope();
        }

        $this->assertEquals($expectedStamps$envelope->all(HandledStamp::class));
    }

    public static function itAddsHandledStampsProvider(): iterable
    {
        $first = new class() extends HandleMessageMiddlewareTestCallable {
            public function __invoke()
            {
                return 'first result';
            }
Home | Imprint | This part of the site doesn't use cookies.