How to recreate the orders context in order to send out emails in Shopware 6

I am creating a console task to ship orders based on XML files (How to add a shipment (tracking code + change status to shipped) programmatically?
) which I import.

Currently I am using

$context = Context::createDefaultContext();

And create a shipment:

    $this->deliveryRepository->update([
        [
            'id' => $deliveryId,
            'trackingCodes' => [$trackingCode]
        ]
    ], $context);

    $context->addExtension(
        MailSendSubscriber::MAIL_CONFIG_EXTENSION,
        new MailSendSubscriberConfig(false)
    );

    $this->orderService->orderDeliveryStateTransition(
        $deliveryId,
        'ship',
        new ParameterBag(),
        $context
    );

This does not send out the shipment confirmation mail.

I am assuming the reason is, because I am in the default context.

Can I / should I recreate the context from the Storefront where the order was placed in? How does this work?
(maybe using \Shopware\Core\System\SalesChannel\Context\BaseContextFactory::create ? but this is tagged as @internal )

Or is it okay to use the default context here (see Shopware 6 get context in scheduled task) and is the problem something else?

EDIT:

$context = $this->baseContextFactory->create($order->getSalesChannelId())->getContext();

does work, but I still do not receive emails.

>Solution :

You can inject the Shopware\Core\Checkout\Cart\Order\OrderConverter service to assemble a SalesChannelContext based on an order. You can then get the Context from the SalesChannelContext.

$salesChannelContext = $this->orderConverter->assembleSalesChannelContext($order, Context::createDefaultContext());
$context = $salesChannelContext->getContext();

Leave a Reply