PHP code example of tobento / service-mail

1. Go to this page and download the library: Download tobento/service-mail library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tobento / service-mail example snippets


use Tobento\Service\Mail\MailerInterface;
use Tobento\Service\Mail\Message;

class SomeService
{
    public function send(MailerInterface $mailer): void
    {
        $message = (new Message())
            ->from('[email protected]')
            ->to('[email protected]')
            //->cc('[email protected]')
            //->bcc('[email protected]')
            //->replyTo('[email protected]')
            ->subject('Subject')
            //->textTemplate('welcome-text')
            //->htmlTemplate('welcome')
            //->text('Lorem Ipsum')
            ->html('<p>Lorem Ipsum</p>');

        $mailer->send($message);
    }
}

use Tobento\Service\Mail\Message;
use Tobento\Service\Mail\Address;

$message = (new Message())
    // email address as a simple string:
    ->from('[email protected]')
    
    // email address and name (optional) as object:
    ->from(new Address('[email protected]', 'Name'))
    
    ->replyTo('[email protected]')
    
    // the following methods support multiple addresses
    // as strings or objects:
    ->to('[email protected]', '[email protected]')
    
    ->to(
        new Address('[email protected]'),
        new Address('[email protected]')
    )
    
    ->cc('[email protected]', new Address('[email protected]'))
    
    ->bcc('[email protected]', new Address('[email protected]'));

use Tobento\Service\Mail\Message;
use Tobento\Service\Mail\Template;

$message = (new Message())
    // content defined as a string:
    ->subject('Subject')
    ->text('Lorem Ipsum')
    ->html('<p>Lorem Ipsum</p>')
    
    // content defined with a template object:
    ->text(new Template(
        name: 'welcome-text',
        data: ['name' => 'John'],
    ))
    
    ->html(new Template('welcome', []))    
    
    // using template methods:
    ->textTemplate(name: 'welcome-text', data: [])
    
    ->htmlTemplate('welcome', []);

use Tobento\Service\Mail\Message;
use Tobento\Service\Mail\Parameter;
use Tobento\Service\Mail\Address;

$message = (new Message())
    // Text header:
    ->parameter(new Parameter\TextHeader(
        name: 'X-Custom-Header',
        value: 'value',
    ))
    
    // Id header:
    ->parameter(new Parameter\IdHeader(
        name: 'References',
        ids: ['[email protected]', '[email protected]'],
    ))
    
    // Path header:
    ->parameter(new Parameter\PathHeader(
        name: 'Return-Path',
        address: '[email protected]',
        
        // or as object
        // address: new Address('[email protected]'),
    ));

use Tobento\Service\Mail\Message;
use Tobento\Service\Mail\Parameter;
use Tobento\Service\Filesystem\File;
use Psr\Http\Message\StreamInterface;

$message = (new Message())
    // File defined as string:
    ->parameter(new Parameter\File(
        file: '/path/to/document.pdf',
        
        // optional parameters:
        filename: 'Document',
        mimeType: 'application/pdf',
    ))

    // File defined with File object:
    ->parameter(new Parameter\File(
        file: new File('/path/to/document.pdf'),
    ))

    // StreamFile:
    ->parameter(new Parameter\StreamFile(
        stream: $stream, // StreamInterface
        filename: 'Filename.png',
        
        // optional parameters:
        mimeType: 'image/png',        
    ))
    
    // ResourceFile:
    ->parameter(new Parameter\ResourceFile(
        resource: fopen('/path/to/image.png', 'r+'),
        filename: 'Image.png',
        
        // optional parameters:
        mimeType: 'image/png',        
    ));    

use Tobento\Service\Mail\Message;
use Tobento\Service\Mail\Parameter;

$message = (new Message())
    // Tags:
    ->parameter(new Parameter\Tags(['tagname']))
    
    // Metadata:
    ->parameter(new Parameter\Metadata([
        'name' => 'value',
    ]));

use Tobento\Service\Mail\Message;
use Tobento\Service\Mail\Parameter;

$message = (new Message())
    ->parameter(new Parameter\Queue(
        // you may specify the queue to be used:
        name: 'secondary',
        
        // you may specify a delay in seconds:
        delay: 30,
        
        // you may specify how many times to retry:
        retry: 3,
        
        // you may specify a priority:
        priority: 100,
        
        // you may specify if you want to encrypt the message:
        encrypt: true,
        
        // you may specify if you want to render the message templates
        // before queuing:
        renderTemplates: false, // true default
    ));

use Tobento\Service\Mail\Message;
use Tobento\Service\Mail\Parameter;

$message = (new Message())
    ->parameter(new Parameter\SendWithMailer(name: 'mailchimp'));

use Tobento\Service\Mail\ParameterInterface;

class CustomParameter implements ParameterInterface
{
    /**
     * Create a new CustomParameter.
     *
     * @param string $name
     */
    public function __construct(
        protected string $name
    ) {}
    
    /**
     * Returns the name.
     *
     * @return string
     */
    public function name(): string
    {
        return $this->name;
    }
}

use Tobento\Service\Mail\NullMailer;
use Tobento\Service\Mail\MailerInterface;

$mailer = new NullMailer(name: 'null');

var_dump($mailer instanceof MailerInterface);
// bool(true)

use Tobento\Service\Mail\Mailers;
use Tobento\Service\Mail\MailersInterface;
use Tobento\Service\Mail\MailerInterface;

$mailers = new Mailers(
    $mailer, // MailerInterface
    $anotherMailer, // MailerInterface
);

var_dump($mailers instanceof MailersInterface);
// bool(true)

var_dump($mailers instanceof MailerInterface);
// bool(true)

use Tobento\Service\Mail\LazyMailers;
use Tobento\Service\Mail\MailersInterface;
use Tobento\Service\Mail\MailerInterface;
use Tobento\Service\Mail\MailerFactoryInterface;
use Tobento\Service\Mail\Symfony;
use Psr\Container\ContainerInterface;

$mailers = new LazyMailers(
    container: $container, // ContainerInterface
    mailers: [
        // using a factory:
        'default' => [
            // factory must implement MailerFactoryInterface
            'factory' => Symfony\SmtpMailerFactory::class,
            
            'config' => [
                'encryption' => '',
                'host' => 'host',
                'user' => 'user',
                'password' => '********',
                'port' => 465,

                // you may define default addresses and parameters
                // or set to null if defaults are used from email factory.
                'defaults' => [
                    'from' => '[email protected]',
                ],
            ],
        ],
        
        // using a closure:
        'secondary' => static function (string $name, ContainerInterface $c): MailerInterface {
            // create mailer ...
            return $mailer;
        },
        
        'mailchimp' => [
            // ...
        ],
    ],
);

var_dump($mailers instanceof MailersInterface);
// bool(true)

var_dump($mailers instanceof MailerInterface);
// bool(true)

use Tobento\Service\Mail\Message;

$message = (new Message())
    //...
    ->htmlTemplate(
        name: 'email/welcome',
        data: ['name' => 'John', 'text' => 'Lorem ipsum'],
    );

<!DOCTYPE html>
<html>
    <head>
        <title><?= $view->esc($message->subject()) 

use Tobento\Service\Mail\RendererInterface;
use Tobento\Service\Mail\TemplateInterface;
use Tobento\Service\Mail\Template;
use Tobento\Service\Mail\Message;

class SomeController
{
    public function renderEmail(RendererInterface $renderer): string
    {
        // by using a template object:
        $content = $renderer->renderTemplate(
            template: new Template(
                name: 'email/welcome',
                data: ['name' => 'John'],
            ),
            
            // you may not want to convert css
            // to inline styles for web views
            // as you might use CSP with blocking inline css.
            withInlineCssStyles: false, // true is default
        );
        
        // render message contents:
        $message = (new Message())
            ->htmlTemplate('email/welcome', ['name' => 'John']);
        
        if ($message->getHtml() instanceof TemplateInterface) {
            $content = $renderer->renderTemplate($message->getHtml());
        }
        
        return $content;
    }
}

use Tobento\Service\Mail\MailerInterface;
use Tobento\Service\Mail\Symfony;
use Tobento\Service\Mail\ViewRenderer;
use Tobento\Service\View;
use Tobento\Service\Dir;
use Symfony\Component\Mailer\Transport\Dsn;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransportFactory;

// create the renderer:
$renderer = new ViewRenderer(
    new View\View(
        new View\PhpRenderer(
            new Dir\Dirs(
                new Dir\Dir('dir/views/'),
            )
        ),
        new View\Data(),
        new View\Assets('dir/src/', 'https://example.com/src/')
    )
);

// create email factory:
$emailFactory = new Symfony\EmailFactory(
    renderer: $renderer,
);

// create the transport:
$transport = (new EsmtpTransportFactory())->create(new Dsn(
    'smtp',
    'host',
    'user',
    'password',
    465,
    [],
));

// create the mailer:
$mailer = new Symfony\Mailer(
    name: 'default',
    emailFactory: $emailFactory,
    transport: $transport,
);

var_dump($mailer instanceof MailerInterface);
// bool(true)

use Tobento\Service\Mail\Symfony;
use Psr\EventDispatcher\EventDispatcherInterface;

// create the mailer:
$mailer = new Symfony\Mailer(
    name: 'default',
    emailFactory: $emailFactory,
    transport: $transport,
    
    // pass your event dispatcher:
    eventDispatcher: $dispatcher, // EventDispatcherInterface
);

use Tobento\Service\Mail\Symfony;
use Tobento\Service\Mail\QueueHandlerInterface;
use Tobento\Service\Mail\RendererInterface;
use Tobento\Service\Mail\Queue\QueueHandler;
use Tobento\Service\Queue\QueueInterface;

// create the mailer:
$mailer = new Symfony\Mailer(
    name: 'default',
    emailFactory: $emailFactory,
    transport: $transport,
    
    // pass your queue handler implementing QueueHandlerInterface:
    queueHandler: new QueueHandler(
        queue: $queue, // QueueInterface
        renderer: $renderer, // RendererInterface
        // you may define the default queue used if no specific is defined on the message.
        queueName: 'mails', // null|string
    ),
);

use Tobento\Service\Mail\MailerInterface;
use Tobento\Service\Mail\MessageFactoryInterface;
use Tobento\Service\Mail\MessageFactory;
use Tobento\Service\Queue\JobProcessor;
use Tobento\Service\Container\Container;

$container = new Container();
$container->set(MessageFactoryInterface::class, MessageFactory::class);
$container->set(MailerInterface::class, function() {
    // create mailer:
    return $mailer;
});

$jobProcessor = new JobProcessor($container);

use Tobento\Service\Mail\Symfony;
use Tobento\Service\Mail\Address;
use Tobento\Service\Mail\Parameters;
use Tobento\Service\Mail\Parameter;

$emailFactory = new Symfony\EmailFactory(
    renderer: $renderer,
    
    // you may pass default addresses or parameters
    // to be applied to every message created.
    config: [
        'from' => '[email protected]',
        // with object:
        'from' => new Address('[email protected]', 'Name'),
        
        'replyTo' => '[email protected]',
        // with object:
        'replyTo' => new Address('[email protected]'),
        
        // You may define an address to send all emails to:
        'alwaysTo' => '[email protected]',
        // with object:
        'alwaysTo' => new Address('[email protected]'),
        
        'parameters' => new Parameters(
            new Parameter\PathHeader('Return-Path', '[email protected]'),
        ),
    ],
);

// create the mailer:
$mailer = new Symfony\Mailer(
    name: 'default',
    emailFactory: $emailFactory,
    transport: $transport,
);

use Tobento\Service\Mail\Message;

$message = (new Message())
    // will be created from the html:
    //->text('Lorem Ipsum')
    
    ->html('<p>Lorem Ipsum</p>');

use Tobento\Service\Mail\MailerInterface;
use Tobento\Service\Mail\Symfony;
use Tobento\Service\Mail\ViewRenderer;
use Tobento\Service\Mail\Address;
use Tobento\Service\Mail\Parameters;
use Tobento\Service\Mail\Parameter;
use Tobento\Service\View;
use Tobento\Service\Dir;

// create the renderer:
$renderer = new ViewRenderer(
    new View\View(
        new View\PhpRenderer(
            new Dir\Dirs(
                new Dir\Dir('dir/views/'),
            )
        ),
        new View\Data(),
        new View\Assets('dir/src/', 'https://example.com/src/')
    )
);

// create email factory:
$emailFactory = new Symfony\EmailFactory(
    renderer: $renderer,
);

// create the factory:
$factory = new Symfony\DsnMailerFactory($emailFactory);

// create the mailer:
$mailer = $factory->createMailer(name: 'default', config: [
    'dsn' => 'smtp://user:[email protected]:port',
    
    // If the username, password or host contain
    // any character considered special in a URI
    // (such as +, @, $, #, /, :, *, !),
    // use the following instead of dsn above:
    //'scheme' => 'smtp',
    //'host' => 'host',
    //'user' => 'user',
    //'password' => '********',
    //'port' => 465,
    
    // you may define default addresses and parameters
    // or set to null if defaults are used from email factory.
    'defaults' => [
        'from' => '[email protected]',
    ],
]);

var_dump($mailer instanceof MailerInterface);
// bool(true)

use Tobento\Service\Mail\MailerInterface;
use Tobento\Service\Mail\Symfony;
use Tobento\Service\Mail\ViewRenderer;
use Tobento\Service\Mail\Address;
use Tobento\Service\Mail\Parameters;
use Tobento\Service\Mail\Parameter;
use Tobento\Service\View;
use Tobento\Service\Dir;

// create the renderer:
$renderer = new ViewRenderer(
    new View\View(
        new View\PhpRenderer(
            new Dir\Dirs(
                new Dir\Dir('dir/views/'),
            )
        ),
        new View\Data(),
        new View\Assets('dir/src/', 'https://example.com/src/')
    )
);

// create email factory:
$emailFactory = new Symfony\EmailFactory(
    renderer: $renderer,
);

// create the factory:
$factory = new Symfony\SmtpMailerFactory($emailFactory);

// create the mailer:
$mailer = $factory->createMailer(name: 'default', config: [
    'encryption' => '',
    'host' => 'host',
    'user' => 'user',
    'password' => '********',
    'port' => 465,
    
    // you may define default addresses and parameters
    // or set to null if defaults are used from email factory.
    'defaults' => [
        'from' => '[email protected]',
    ],
]);

var_dump($mailer instanceof MailerInterface);
// bool(true)

use Tobento\Service\Mail\Symfony;
use Tobento\Service\Mail\MessageInterface;
use Tobento\Service\Mail\ParameterInterface;
use Symfony\Component\Mime\Email;

class CustomizedEmailFactory extends Symfony\EmailFactory
{
    /**
     * Create email from message.
     *
     * @param MessageInterface $message
     * @return Email
     */
    public function createEmailFromMessage(MessageInterface $message): Email
    {
        $email = parent::createEmailFromMessage($message);
        
        // filter your custom parameters:
        $parameters = $message->parameters()->filter(
            fn(ParameterInterface $p): bool => $p instanceof CustomParameter
        );
        
        // do something with it:
        foreach($parameters as $parameter) {}
    }
}