Skip the setup. Our team will have you taking orders in 24 hours. Get started →
Advanced

Mail

Introduction Driver prerequisites Configuration Writing mail Creating mail views Creating mail templates Creating mail layouts Creating mail partials Ma...

TastyIgniter uses the Laravel Mail component to send emails. The Mail component provides a clean, simple API which allows you to send emails through a variety of drivers, including SMTP, Mailgun, Postmark and Amazon SES.

To use the Mailgun, Postmark and Amazon SES drivers, install the required dependencies via Composer.

composer require symfony/mailgun-mailer symfony/http-client
composer require symfony/postmark-mailer symfony/http-client
composer require aws/aws-sdk-php

Next, you can configure your mail settings from the Manage > Settings > Mail admin settings page or through the mail configuration file located at config/mail.php. In this file, you may configure the default mail driver, mail sending options, and mail "from" address. For API based drivers such as Mailgun, Postmark, and MailerSend, verify that your config/services.php configuration file contains the required credentials for your mail service.

If you want to configure your mail settings through the mail configuration file instead of the admin interface, you can force the use of the configuration file by adding the following to the boot method of your AppServiceProvider:

use Igniter\Flame\Support\Facades\Igniter;

public function boot()
{
    Igniter::useMailerConfigFile();
}

In TastyIgniter, you can send mail messages using either mail templates or mail views. Mail templates can be managed through the Design > Mail templates admin page, where their content is built from blocks with the mail builder. On the other hand, mail views supplied by the application or extension are stored in the resources/views directory within the extension's directory.

Optionally, you can register mail views in the Extension class with the registerMailTemplates method. This enables automatic generation of mail templates for easy customization via the admin interface.

All mail messages support using Blade and Markdown syntax for markup.

Mail views are stored in the file system, and the mail code is used to represent the path to the view file. For example, sending mail with the code vendor.extension::mail.message would use the content in the corresponding file at vendor/extension/views/mail/message.blade.php.

The mail view file content can include up to 3 sections: configuration, plain text, and HTML markup. These sections are separated using the == sequence. For example:

subject = "Your order has been placed"
==
Hello {{ $customer->first_name }},

Your order has been placed successfully.

Thank you for your order.
==
<p>Hello {{ $customer->first_name }},</p>

<p>Your order has been placed successfully.</p>

<p>Thank you for your order.</p>

The configuration section sets the mail view parameters. The following configuration parameters are supported:

Parameter Description
subject the mail message subject, required.
layout the mail layout code, optional. Default value is default.

The plain text section is optional, while the configuration and HTML markup sections are required.

subject = "Your order has been placed"
==
<p>Hello {{ $customer->first_name }},</p>

<p>Your order has been placed successfully.</p>

<p>Thank you for your order.</p>

Mail templates are used to define the structure of the mail message. You can create mail templates in the admin interface by navigating to Design > Mail templates. The code specified in the template is a unique identifier and cannot be changed once created.

In the admin interface, the content of a mail template is built from blocks with the mail builder. The markup of a template can no longer be written or edited there. The subject may use variables, such as {{ $order_number }}, any other Blade syntax in the subject is shown as typed.

A mail template supplied as a mail view file is written by hand. Here is an example of a simple mail template:

subject: Your order has been placed
==
<p>Hello {{ $customer->first_name }},</p>

<p>Your order has been placed successfully.</p>

<p>Thank you for your order.</p>

Mail layouts can be created by navigating to Design > Mail templates > Layouts in the admin interface. Mail layouts are used to define the structure of the mail message, including the header, footer, and other common elements. The code specified in the layout is a unique identifier and cannot be changed once created. Like mail templates, layouts are built from blocks with the mail builder in the admin interface, with a content block marking where the mail message is placed.

By default, TastyIgniter comes with a default mail layout that can be used as a starting point for creating custom mail layouts.

Here is an example of a simple mail layout view file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <style type="text/css">
        {{ $custom_css }}
        {{ $layout_css }}
    </style>
    <header>
        <h1>{{ $subject }}</h1>
    </header>

    <main>
        {!! $body !!}
    </main>

    <footer>
        <p>&copy; {{ date('Y') }} TastyIgniter</p>
    </footer>
</body>
</html>

In this example, the layout includes a header, main content, and footer sections. The {{ $custom_css }} variable is used to include custom CSS styles in the mail layout, and the {{ $layout_css }} variable is used to include the mail layout CSS styles defined in the admin interface. The {{ $subject }} and {!! $body !!} variables are used to include the mail message subject and content, respectively.

Mail partials are reusable components that can be included in mail templates and layouts. You can create mail partials by navigating to Design > Mail templates > Partials in the admin interface. The code specified in the partial is a unique identifier and cannot be changed once created. Partials are also built with the mail builder, and can define parameters that are filled in where the partial is used.

Here is an example of a simple mail partial view file:

name = "Footer"
==
-------------------
{{ $slot }}
==
<p>{{ $slot }}</p>

You can include the mail partial in a mail template or layout using the @partial directive:

@partial('footer')
<p>&copy; {{ date('Y') }} TastyIgniter</p>
@endpartial

You may access all the data passed to the mail view or template by using the {{ $variable }} syntax. For example, if you pass a $customer_name variable to the mail view, you can access it in the view like this:

<p>Hello {{ $customer_name }},</p>

You can attach files to your emails using the attach method on the Mail facade. The attach method accepts the full path to the file as its first argument:

use Illuminate\Support\Facades\Mail;

Mail::send('vendor.extension::mail.message', $data, function($message) {
    // ...
    $message->attach('/path/to/file');
});

To embed media in your emails, you can use the embed method on the $message variable:

<body>
    <img src="{{ $message->embed($imagePath) }}">
</body>

To embed raw data in your emails, you can use the embedData method on the $message variable. This method accepts the raw data and the name of the file as its first and second arguments, respectively:

<body>
    <img src="{{ $message->embedData($data, 'name.jpg') }}">
</body>

To send a mail template in TastyIgniter, you can use the sendTemplate method on the Mail facade. This method accepts the code of the mail template, an array of data to pass to the view, and a closure that receives a message instance which allows you to customize the recipients, subject, and other aspects of the mail message:

use Igniter\System\Helpers\MailHelper;

$data = [];

MailHelper::sendTemplate('vendor.extension::mail.message', $data, function($message) use ($customer) {
    $message->to($customer->email, $customer->name);
});

To queue a mail message, you can use the queueTemplate method on the Mail facade. This method will automatically push the email onto the queue, so it will be sent in the background by a queue worker. This can help to improve the response time of your application by offloading the sending of the email to a background process:

use Igniter\System\Helpers\MailHelper;

$data = [];

MailHelper::queueTemplate('vendor.extension::mail.message', $data, function($message) use ($customer) {
    $message->to($customer->email, $customer->name);
});

The SendsMailTemplate trait provides a convenient way to send mail templates from a model. To use this trait, add it to your model class and define the mailGetData method that returns the mail template variables:

use Igniter\Flame\Mail\SendMailTemplate;

class Order extends Model
{
    use SendMailTemplate;

    public function mailGetData()
    {
        return [
            'customer' => $this->customer,
        ];
    }
}

You can use the mailGetRecipients method to define the recipients of the mail message. The mailGetRecipients method accepts a single $recipientType parameter and returns an array of recipients, where each recipient is an array containing the email address and name of the recipient.

public function mailGetRecipients($recipientType)
{
    return [
        [$this->customer->email, $this->customer->name],
    ];
}

You may also customise the reply-to address by defining the mailGetReplyTo method:

public function mailGetReplyTo()
{
    return [$this->customer->email, $this->customer->name];
}

To send the mail message, use the mailSend method on the model instance, where the first parameter is the mail template code, and the second parameter is the recipient type:

$order = Order::find(1);

$order->mailSend('vendor.extension::mail.message', 'customer');

Possible values for the recipient type are customer, location or admin.

Mail templates, layouts and partials are edited in the admin interface with the mail builder. A mail is a list of blocks, such as a heading, text, button, image, panel or table, shown beside a live preview. Variables are inserted from a picker that lists the variables available to the mail being edited, and the colours of all mails are set from the builder's theme options.

The blocks are compiled to the Blade markup and plain text stored with the template, layout or partial when it is saved. Only markup produced by blocks is stored: arbitrary HTML, Blade and PHP cannot be entered in the admin interface. Mail view files in extensions are not affected and can use any Blade syntax.

When a registered mail view is opened in the builder, its content is turned into blocks. Content that cannot be turned into blocks is kept as a read-only Imported content block that still renders from the original mail view file. To change it, delete the block and rebuild that part with blocks.

Extensions can add their own blocks to the mail builder. A block is a class that extends Igniter\System\Classes\MailBuilder\BaseMailBlock, defines the form fields used to edit its settings, and compiles itself to Blade:

namespace Acme\HelloWorld\MailBlocks;

use Igniter\System\Classes\MailBuilder\BaseMailBlock;
use Igniter\System\Classes\MailBuilder\BladeFragment;
use Igniter\System\Classes\MailBuilder\BladeWriter;
use Igniter\System\Classes\MailBuilder\CompileContext;
use Igniter\System\Classes\MailBuilder\TextWriter;

class Notice extends BaseMailBlock
{
    public function blockDetails(): array
    {
        return [
            'code' => 'notice',
            'name' => 'Notice',
            'icon' => 'fa fa-circle-info',
        ];
    }

    public function defineFields(): array
    {
        return [
            'text' => [
                'label' => 'Text',
                'type' => 'text',
                'default' => 'Thank you for your order',
                'validationRule' => ['required', 'string', 'max:255'],
            ],
        ];
    }

    public function toBlade(array $settings, BladeWriter $writer, CompileContext $context): BladeFragment
    {
        return $writer->tag('p', [
            'style' => $writer->static('text-align: center'),
        ], $writer->text($settings['text'] ?? ''));
    }

    public function toText(array $settings, TextWriter $writer, CompileContext $context): BladeFragment
    {
        return $writer->text($settings['text'] ?? '');
    }
}

The blockDetails method returns the following details:

Key Description
code A unique code for the block, required.
name The block name shown in the builder, can be a language key.
description A short description shown in the builder, optional.
icon The icon CSS class, optional. Defaults to fa fa-cube.
category The group the block is listed under, optional. Defaults to content.
modes Where the block can be used: template, layout and partial, optional. Defaults to all three.
unique When true, the block can only be used once in a mail, optional.
required When true, or a list of modes, a mail of that kind must contain the block, optional.
conditional When true, the block can be shown only when a variable is set or empty, optional. Defaults to true.

The field types supported by defineFields are text, textarea, markdown, select, number, switch, color, url, image, variable, param and table.

Blocks never return raw strings. The toBlade method builds its output with the BladeWriter, which escapes every value: text and markdown write escaped content and keep allowed {{ $variable }} tokens as variables, tag writes an HTML element, var echoes a registered variable, and url, color and number write validated values. The optional toText method builds the plain-text version of the block, blocks without one are left out of the plain-text mail.

Register the blocks by overriding the registerMailBlocks method of the Extension class:

public function registerMailBlocks(): array
{
    return [
        \Acme\HelloWorld\MailBlocks\Notice::class,
    ];
}

To extend or remove existing blocks, register a callback with the MailBlockManager class:

use Igniter\System\Classes\MailBuilder\BaseMailBlock;
use Igniter\System\Classes\MailBuilder\MailBlockManager;

resolve(MailBlockManager::class)->registerCallback(function (MailBlockManager $manager) {
    $manager->extendBlock('button', fn (BaseMailBlock $block) => $block->addFields([
        'tracking_code' => ['label' => 'Tracking code', 'type' => 'text'],
    ]));

    $manager->removeBlock('spacer');
});

To register mail templates, layouts, and partials in the Extension class, you can use the registerMailTemplates, registerMailLayouts, and registerMailPartials methods, respectively. These methods allow you to define the mail templates, layouts, and partials that your extension provides, making them available for customization via the admin interface:

public function registerMailTemplates(): array
{
    return [
        'vendor.extension::mail.message' => 'Registered mail template message',
    ];
}

public function registerMailLayouts(): array
{
    return [
        'vendor.extension::mail.layouts.default' => 'Default Layout',
    ];
}

public function registerMailPartials(): array
{
    return [
        'vendor.extension::mail.partials.footer' => 'Footer partial',
    ];
}

When developing locally, you may want to catch all outgoing mail messages and display them in the browser instead of sending them. You can use the log mail driver to log all outgoing mail messages to the log file. To enable this driver, set the MAIL_DRIVER environment variable to log in your .env file:

MAIL_DRIVER=log

Did this answer your question?

Your feedback helps us improve our help articles.

See a mistake? Edit this page on GitHub

Need more help?

Explore the help center, join the community, or get priority support from the TastyIgniter team.