PHPackages                             tobento/service-mail - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Mail &amp; Notifications](/categories/mail)
4. /
5. tobento/service-mail

ActiveLibrary[Mail &amp; Notifications](/categories/mail)

tobento/service-mail
====================

Mailer interface for PHP applications.

2.0(7mo ago)0933MITPHPPHP &gt;=8.4

Since Nov 5Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/tobento-ch/service-mail)[ Packagist](https://packagist.org/packages/tobento/service-mail)[ Docs](https://www.tobento.ch)[ RSS](/packages/tobento-service-mail/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (7)Dependencies (15)Versions (9)Used By (3)

Mail Service
============

[](#mail-service)

Mailer interface for PHP applications using the [Symfony Mailer](https://github.com/symfony/mailer) as default mailer implementation.

Table of Contents
-----------------

[](#table-of-contents)

- [Getting started](#getting-started)
    - [Requirements](#requirements)
    - [Highlights](#highlights)
- [Documentation](#documentation)
    - [Basic Usage](#basic-usage)
        - [Creating And Sending Messages](#creating-and-sending-messages)
    - [Message](#message)
        - [Email Addresses](#email-addresses)
        - [Contents](#contents)
        - [Headers](#headers)
        - [File Attachments](#file-attachments)
        - [Tags And Metadata](#tags-and-metadata)
        - [Queue](#queue)
        - [Send With Mailer](#send-with-mailer)
        - [Custom Parameters](#custom-parameters)
    - [Mailer](#mailer)
        - [Null Mailer](#null-mailer)
        - [SF Mailer](#sf-mailer)
    - [Mailers](#mailers)
        - [Default Mailers](#default-mailers)
        - [Lazy Mailers](#lazy-mailers)
    - [Templating](#templating)
        - [Writing Views](#writing-views)
        - [Render Templates](#render-templates)
    - [Events](#events)
    - [Symfony](#symfony)
        - [Symfony Mailer](#symfony-mailer)
            - [Events Support](#events-support)
            - [Queue Support](#queue-support)
            - [Default Addresses And Parameters](#default-addresses-and-parameters)
            - [Html To Text Converting](#html-to-text-converting)
        - [Symfony Dsn Mailer Factory](#symfony-dsn-mailer-factory)
        - [Symfony Smtp Mailer Factory](#symfony-smtp-mailer-factory)
        - [Symfony Custom Parameters Support](#symfony-custom-parameters-support)
- [Credits](#credits)

---

Getting started
===============

[](#getting-started)

Add the latest version of the mail service project running this command.

```
composer require tobento/service-mail

```

Requirements
------------

[](#requirements)

- PHP 8.4 or greater

Highlights
----------

[](#highlights)

- Framework-agnostic, will work with any project
- Decoupled design

Documentation
=============

[](#documentation)

Basic Usage
-----------

[](#basic-usage)

### Creating And Sending Messages

[](#creating-and-sending-messages)

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

class SomeService
{
    public function send(MailerInterface $mailer): void
    {
        $message = new Message()
            ->from('from@example.com')
            ->to('to@example.com')
            //->cc('cc@example.com')
            //->bcc('bcc@example.com')
            //->replyTo('replyto@example.com')
            ->subject('Subject')
            //->textTemplate('welcome-text')
            //->htmlTemplate('welcome')
            //->text('Lorem Ipsum')
            ->html('Lorem Ipsum');

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

Check out the available [Mailers](#mailer).

Check out the [Message](#message) to learn more about it.

Message
-------

[](#message)

### Email Addresses

[](#email-addresses)

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

$message = new Message()
    // email address as a simple string:
    ->from('from@example.com')

    // email address and name (optional) as object:
    ->from(new Address('from@example.com', 'Name'))

    ->replyTo('replyto@example.com')

    // the following methods support multiple addresses
    // as strings or objects:
    ->to('to@example.com', 'anotherTo@example.com')

    ->to(
        new Address('to@example.com'),
        new Address('anotherTo@example.com')
    )

    ->cc('cc@example.com', new Address('anotherCc@example.com'))

    ->bcc('bcc@example.com', new Address('anotherBcc@example.com'));
```

### Contents

[](#contents)

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

$message = new Message()
    // content defined as a string:
    ->subject('Subject')
    ->text('Lorem Ipsum')
    ->html('Lorem Ipsum')

    // 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', []);
```

### Headers

[](#headers)

```
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: ['a@example.com', 'b@example.com'],
    ))

    // Path header:
    ->parameter(new Parameter\PathHeader(
        name: 'Return-Path',
        address: 'return@example.com',

        // or as object
        // address: new Address('return@example.com'),
    ));
```

### File Attachments

[](#file-attachments)

```
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',
    ));
```

### Tags And Metadata

[](#tags-and-metadata)

```
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',
    ]));
```

### Queue

[](#queue)

You may queue your message if your mailer is configured to support it.

```
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
    ));
```

Check out the [Symfony Mailer - Queue Support](#queue-support) for support.

### Send With Mailer

[](#send-with-mailer)

You may define a mailer used to send the message if your mailer supports it.

Check out the [Mailers](#mailers) for more detail.

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

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

### Custom Parameters

[](#custom-parameters)

You may write your own parameters in the following way:

```
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;
    }
}
```

Check out the [Symfony Custom Parameters Support](#symfony-custom-parameters-support) for handling your custom parameter.

Mailer
------

[](#mailer)

### Null Mailer

[](#null-mailer)

The `NullMailer::class` does not send any mail message at all which may be useful while developing (or testing).

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

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

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

### SF Mailer

[](#sf-mailer)

Documentation is in the [Symfony Mailer](#symfony-mailer) section.

Mailers
-------

[](#mailers)

You may use the following mailers as your MailerInterface implementation for supporting the [Send With Mailer](#send-with-mailer) parameter.

### Default Mailers

[](#default-mailers)

```
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)
```

### Lazy Mailers

[](#lazy-mailers)

The lazy mailers class creates the mailer only on demand.

```
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' => 'from@example.com',
                ],
            ],
        ],

        // 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)
```

Templating
----------

[](#templating)

The following examples are aimed for the default renderer `Tobento\Service\Mail\ViewRenderer::class`.

### Writing Views

[](#writing-views)

```
use Tobento\Service\Mail\Message;

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

**The welcome view template**

A variable called message, which is an instance of `Tobento\Service\Mail\TemplateMessageInterface::class` is available on every view.

Furthermore, use css file assests to design your template. When the template gets rendered, it will convert them to inline styles for better email clients support.

```
DOCTYPE html>
