如何在 Shopware 6 控制器中发送电子邮件?

Dav*_*vid 2 php email e-commerce symfony shopware

在 Shopware 5 中,有一个mail->send()功能可以发送包含所需模板和内容的电子邮件。Shopware 6 中的功能名称是什么?

PS 我看到一些我认为需要的文件,欢迎发送一些邮件示例。

Shopware\Core\Content\MailTemplate\Service\MessageFactory.php
Shopware\Core\Content\MailTemplate\Service\MailSender.php
Run Code Online (Sandbox Code Playgroud)

Chr*_*sin 7

在 Shopware 6 中,您还有 Mailservice,它为您提供了一个send() 方法

因此,基本上使用该服务的一个非常简单的示例是:

public function __construct(
    MailServiceInterface $mailService,
) {
    $this->mailService = $mailService;
}

private function sendMyMail(SalesChannelContext $salesChannelContext): void
{
    $data = new ParameterBag();
    $data->set(
        'recipients',
        [
            'foo@bar.com' => 'John Doe'
        ]
    );

    $data->set('senderName', 'I am the Sender');

    $data->set('contentHtml', 'Foo bar');
    $data->set('contentPlain', 'Foo bar');
    $data->set('subject', 'The subject');
    $data->set('salesChannelId', $salesChannelContext->getSalesChannel()->getId());

    $this->mailService->send(
        $data->all(),
        $salesChannelContext->getContext(),
    );
}
Run Code Online (Sandbox Code Playgroud)

还要确保在您的services.xml.

<service id="Your\Namespace\Services\YourSendService">
  <argument id="Shopware\Core\Content\MailTemplate\Service\MailService" type="service"/>
</service>
Run Code Online (Sandbox Code Playgroud)

电子邮件模板

如果您想使用电子邮件模板,还有一个如何在插件中添加邮件模板的方法

如果您有电子邮件模板,则需要在发送电子邮件之前获取它。然后,您可以从电子邮件模板中获取内容以将这些值传递给该send()方法。

private function getMailTemplate(SalesChannelContext $salesChannelContext, string $technicalName): ?MailTemplateEntity
{
    $criteria = new Criteria();
    $criteria->addFilter(new EqualsFilter('mailTemplateType.technicalName', $technicalName));
    $criteria->setLimit(1);

    /** @var MailTemplateEntity|null $mailTemplate */
    $mailTemplate = $this->mailTemplateRepository->search($criteria, $salesChannelContext->getContext())->first();

    return $mailTemplate;
}
Run Code Online (Sandbox Code Playgroud)

您可以稍后设置来自您的电子邮件模板(也可以在管理中使用)的电子邮件值,而不是在您的发送方法中对其进行硬编码。

$data->set('contentHtml', $mailTemplate->getContentHtml());
$data->set('contentPlain', $mailTemplate->getContentPlain());
$data->set('subject', $mailTemplate->getSubject());
Run Code Online (Sandbox Code Playgroud)