HowTo: Create and register a mail provider

Edit on GitHub
Info

Spryker lets you send emails via the Symfony mailer component. In order to use the component, see Install the Mailing and Notifications feature guide. For information on how to you use, see Install the Mailing and Notifications feature guide.

This guide shows how to create and register a mail provider you want to use.

A mail provider is defined in the provider class. Since each provider behaves differently, each provider’s class differs from the rest.

Create and register a mail provider

  1. Create a class that implements MailProviderPluginInterface.
  2. In the Mail module, register your provider.
  3. To register a provider, add it to MailProviderCollection by including the provider in MailDependencyProvider:
<?php
namespace Pyz\Zed\Mail;

...

public function provideBusinessLayerDependencies(Container $container)
{
    ...

    $container->extend(self::MAIL_PROVIDER_COLLECTION, function (MailProviderCollectionAddInterface $mailProviderCollection) {
        $mailProviderCollection->addProvider(new YourProviderPlugin(), MailConfig::MAIL_TYPE_ALL);

        return $mailProviderCollection;
    });

    ...
}
...

By using $container->extend(), you get MailProviderCollectionAddInterface, where you can add your provider. MailProviderCollectionAddInterface::addProvider() takes the provider you want to use as the first argument, and a MailType or a list of MailType classes which this provider must use as the second argument.

As you can see in the previous example, a provider is registered to all MailType classes by using MailConfig::MAIL_TYPE_ALL. If you want the provider to handle only a specific MailType, use the MailType constant from your MailTypePlugin. For example, you can use CustomerRegistrationMailTypePlugin::MAIL_TYPE. For information about creating and registering a MailTypePlugin, see HowTo: Creating and registering a MailTypePlugin.

Use more than one provider

To send emails through more than one provider, register each of the desired providers in the Mail module. You can even create a scenario where all marketing emails go through provider A, while all other emails go through provider B. In the previous section, this method is used to register one provider to all types. The following example demonstrates how to wire up more than one provider:

<?php
namespace Pyz\Zed\Mail;

...

public function provideBusinessLayerDependencies(Container $container)
{
    ...

    $container->extend(self::MAIL_PROVIDER_COLLECTION, function (MailProviderCollectionAddInterface $mailProviderCollection) {
        $mailProviderCollection
            ->addProvider(new ProviderAPlugin(), [MailTypeA::MAIL_TYPE, MailTypeB::MAIL_TYPE])
            ->addProvider(new ProviderBPlugin(), MailTypeC::MAIL_TYPE);

        return $mailProviderCollection;
    });

    ...
}
...

If a MailType class can be handled by more than one provider, the email is sent by both of them.