### Run Mailcoach Queue Worker Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/as-a-standalone-app This command starts a queue worker specifically for Mailcoach queues, allowing you to process background tasks. It's an alternative to the standard Laravel `queue:work` command. ```bash php artisan mailcoach:work ``` -------------------------------- ### Publish and Run Mailcoach Migrations Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Publishes the necessary database migration files for Mailcoach and then executes them to create the required tables in your database. This is a crucial step after installing the package. ```bash php artisan vendor:publish --tag=mailcoach-migrations php artisan migrate ``` -------------------------------- ### Configure Laravel Horizon for Mailcoach Queues Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Sets up dedicated queues and supervisors for Mailcoach tasks within Laravel Horizon. This involves defining 'mailcoach-general' and 'mailcoach-heavy' configurations for both production and local environments in `config/horizon.php`. It also requires adding a 'mailcoach-redis' connection in `config/queue.php`, ensuring proper Redis setup for queue management. ```php 'environments' => [ 'production' => [ 'supervisor-1' => [ 'connection' => 'redis', 'queue' => ['default'], 'balance' => 'simple', 'processes' => 10, 'tries' => 2, 'timeout' => 60 * 60, ], 'mailcoach-general' => [ 'connection' => 'mailcoach-redis', 'queue' => ['mailcoach-schedule', 'mailcoach', 'mailcoach-feedback', 'send-mail', 'send-automation-mail'], 'balance' => 'auto', 'processes' => 10, 'tries' => 2, 'timeout' => 60 * 60, ], 'mailcoach-heavy' => [ 'connection' => 'mailcoach-redis', 'queue' => ['send-campaign'], 'balance' => 'auto', 'processes' => 3, 'tries' => 1, 'timeout' => 60 * 60, ], ], 'local' => [ 'supervisor-1' => [ 'connection' => 'redis', 'queue' => ['default'], 'balance' => 'simple', 'processes' => 10, 'tries' => 2, 'timeout' => 60 * 60, ], 'mailcoach-general' => [ 'connection' => 'mailcoach-redis', 'queue' => ['mailcoach-schedule', 'mailcoach', 'mailcoach-feedback', 'send-mail', 'send-automation-mail'], 'balance' => 'auto', 'processes' => 10, 'tries' => 2, 'timeout' => 60 * 60, ], 'mailcoach-heavy' => [ 'connection' => 'mailcoach-redis', 'queue' => ['send-campaign'], 'balance' => 'auto', 'processes' => 3, 'tries' => 1, 'timeout' => 60 * 60, ], ], ], ``` ```php 'connections' => [ // ... 'mailcoach-redis' => [ 'driver' => 'redis', 'connection' => 'default', 'queue' => env('REDIS_QUEUE', 'default'), 'retry_after' => 11 * 60, 'block_for' => null, ], ``` -------------------------------- ### Serve Mailcoach Application Locally Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/as-a-standalone-app Instructions for serving your Mailcoach application during development. You can use the built-in Artisan server or tools like Laravel Valet. ```bash php artisan serve ``` -------------------------------- ### Add Mailcoach Package via Composer Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Installs the spatie/laravel-mailcoach package into your Laravel project using Composer. Ensure the repository and authentication are correctly configured beforehand. ```bash composer require "spatie/laravel-mailcoach:^8.0" ``` -------------------------------- ### Publish Mailcoach Configuration File Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Publishes the main configuration file for Mailcoach, allowing for customization of its settings. This command makes the `mailcoach.php` file available for modification. ```bash php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-config" ``` -------------------------------- ### Install doctrine/dbal for Migrations Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading This command installs the `doctrine/dbal` package, which is required for Mailcoach's rename migrations to function correctly. This is necessary for updating the database schema in Mailcoach v9. ```bash composer require doctrine/dbal ``` -------------------------------- ### Create First Mailcoach User with Artisan Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/as-a-standalone-app Generate the initial user for your Mailcoach application using the provided Artisan command. This user can then be used to log in to the Mailcoach interface. New users can be added through the Mailcoach UI. ```bash php artisan mailcoach:make-user ``` -------------------------------- ### Configure Composer Repository and Authentication Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Adds the spatie/mailcoach package repository to your Composer configuration and sets up authentication credentials for accessing the private repository. This involves modifying `composer.json` and creating an `auth.json` file. ```json { "repositories": [ { "type": "composer", "url": "https://satis.spatie.be" } ] } ``` ```json { "http-basic": { "satis.spatie.be": { "username": "", "password": "" } } } ``` -------------------------------- ### Determine Composer Home Directory Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app A utility command to find the location of the Composer home directory on Unix-like systems. This is useful for determining the correct place to put the `auth.json` file. ```bash composer config --list --global | grep home ``` -------------------------------- ### Create Mailcoach Laravel Application with Composer Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/as-a-standalone-app Use Composer to create a new Laravel application with Mailcoach preinstalled. This command sets up the basic application structure, including authorization screens and user management. ```bash composer create-project spatie/Mailcoach ``` -------------------------------- ### Register Mailcoach Route Macro Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Adds the necessary route macro to handle Mailcoach's functionalities, such as subscription confirmations and tracking. It's recommended to place this within the `boot` method of your `RouteServiceProvider`. ```php Route::mailcoach('mailcoach'); ``` -------------------------------- ### Schedule Mailcoach Tasks with Artisan Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/as-a-standalone-app Ensure the Laravel scheduler runs every minute to execute scheduled tasks for Mailcoach. This is a standard Laravel scheduler command. ```bash php artisan schedule:run ``` -------------------------------- ### PHP Custom Segment Example (Configurable Character) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations This PHP class defines a customizable segment that filters subscribers based on a configurable starting character in their email address. It includes a constructor to set the character and implements the `shouldSend` method for filtering. ```php class OnlyEmailAddressesStartingWith extends Segment { public string $character; public function __construct(string $character) { $this->character = $character; } public function shouldSend(Subscriber $subscriber): bool { return Str::startsWith($subscriber->email, $this->character); } } ``` -------------------------------- ### Verify Composer Authentication Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Tests if Composer can correctly access the private repository using the credentials stored in `auth.json`. This command should display your authentication details if configured correctly. ```bash composer config --list --global | grep satis.spatie.be ``` -------------------------------- ### Publish Mailcoach Assets and Configure Auto-Publishing Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Publishes all assets required by Mailcoach, including migrations and other necessary files. It also provides a recommended configuration to automatically republish these assets on Composer updates. ```bash php artisan mailcoach:publish ``` ```json "scripts": { "post-update-cmd": [ "@php artisan mailcoach:publish" ] } ``` -------------------------------- ### PHP Custom Segment Example (Subscribers Starting with 'a') Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations This PHP code defines a custom segment class that extends Mailcoach's `Segment` class. It implements the `shouldSend` method to filter subscribers whose email addresses begin with the letter 'a'. ```php class OnlyEmailAddressesStartingWithA extends Segment { public function shouldSend(Subscriber $subscriber): bool { return Str::startsWith($subscriber->email, 'a'); } } ``` -------------------------------- ### Create and Start a Mailcoach Automation (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Demonstrates the creation of a new automation in Mailcoach using a fluent interface. It includes setting the name, target email list, run interval, trigger condition (e.g., SubscribedTrigger), and a sequence of actions. Dependencies include Mailcoach, CarbonInterval, and specific trigger classes. ```PHP Automation::create() ->name('Welcome email') ->to($emailList) ->runEvery(CarbonInterval::minute()) ->triggerOn(new SubscribedTrigger) ->chain([ new SendAutomationMailAction($automationMail), ]) ->start(); ``` -------------------------------- ### Create Custom Segment - Starting Character Match in PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Defines a custom segment class that filters subscribers based on whether their email address starts with a specific character. This class extends `SpatieMailcoachSupportSegmentsSegment` and implements the `shouldSend` method for filtering logic. ```php use Spatie\Mailcoach\Domain\Subscriber\Models\Subscriber; use Spatie\Mailcoach\Support\Segments\Segment; use Illuminate\Support\Str; class OnlyEmailAddressesStartingWithA extends Segment { public function shouldSend(Subscriber $subscriber): bool { return Str::startsWith($subscriber->email, 'a'); } } ``` ```php Campaign::create() ->content($yourHtml) ->segment(OnlyEmailAddressesStartingWithA::class) ->sendTo($emailList); ``` -------------------------------- ### WaitAction Class Implementation Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Provides a complete example of the WaitAction class, extending AutomationAction. It includes dependency injection for CarbonInterval, methods for UI component identification ('getComponent'), data serialization ('make', 'toArray'), and handling user-defined time intervals. ```php class WaitAction extends AutomationAction { public CarbonInterval $interval; public function __construct(CarbonInterval $interval) { parent::__construct(); $this->interval = $interval; } public static function getComponent(): ?string { return 'wait-action'; } public static function make(array $data): self { return new self(CarbonInterval::createFromDateString("{$data['length']} {$data['unit']}")); } public function toArray(): array { [$length, $unit] = explode(' ', $this->interval->forHumans()); return [ 'length' => $length, 'unit' => Str::plural($unit), ]; } } ``` -------------------------------- ### Create Custom Campaign Placeholder Replacer (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Example implementation of a custom placeholder replacer for Mailcoach campaigns. This class defines how a placeholder like '::webviewUrl::' is replaced with actual content. ```php namespace Spatie\Mailcoach\Support\Replacers; use Spatie\Mailcoach\Domain\Campaign\Models\Campaign; use Spatie\Mailcoach\Domain\Campaign\Support\Replacers\CampaignReplacer; class WebviewReplacer implements CampaignReplacer { public function helpText(): array { return [ 'webviewUrl' => 'This url will display the html of the campaign', ]; } public function replace(string $html, Campaign $campaign): string { $webviewUrl = $campaign->webviewUrl(); return str_ireplace('::webviewUrl::', $webviewUrl, $html); } } ``` -------------------------------- ### Example View for a Mailcoach Automation Action Component (Blade) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Renders the UI for a Mailcoach automation action component using Blade. It wraps the content in `` to ensure proper display of edit and save buttons. Includes form fields for 'Length' and 'Unit' with custom Mailcoach components. ```blade {{__mc('Wait for ') }} {{ ($length && $unit && $interval = \Carbon\CarbonInterval::createFromDateString("{$length} {$unit}")) ? $interval->cascade()->forHumans() : '…' }}
``` -------------------------------- ### PHP Personalized Replacer Example (UnsubscribeUrlReplacer) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations This PHP class implements the PersonalizedReplacer interface to dynamically replace placeholders in emails. It provides help text for available replacements and handles the logic for replacing unsubscribe URLs and tag-specific unsubscribe URLs using the Send object. ```php namespace Spatie\Mailcoach\Domain\Automation\Support\Replacers; use Spatie\Mailcoach\Domain\Shared\Models\Send; class UnsubscribeUrlReplacer implements PersonalizedReplacer { public function helpText(): array { return [ 'unsubscribeUrl' => __mc('The URL where users can unsubscribe'), 'unsubscribeTag::your tag' => __mc('The URL where users can be removed from a specific tag'), ]; } public function replace(string $text, Send $pendingSend): string { $unsubscribeUrl = $pendingSend->subscriber->unsubscribeUrl($pendingSend); $text = str_ireplace('::unsubscribeUrl::', $unsubscribeUrl, $text); preg_match_all('/::unsubscribeTag::(.*)::/', $text, $matches, PREG_SET_ORDER); foreach ($matches as $match) { [$key, $tag] = $match; $unsubscribeTagUrl = $pendingSend->subscriber->unsubscribeTagUrl($tag); $text = str_ireplace($key, $unsubscribeTagUrl, $text); } return $text; } } ``` -------------------------------- ### Schedule Mailcoach Console Commands Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app Schedules various Mailcoach commands to run at different intervals (e.g., every minute, hourly, daily). This ensures automated tasks like sending emails, processing triggers, and cleanup are executed regularly. Ensure your console kernel is set up to run these scheduled tasks. ```php // in app/Console/Kernel.php protected function schedule(Schedule $schedule) { // ... $schedule->command('mailcoach:send-automation-mails')->everyMinute(); $schedule->command('mailcoach:send-scheduled-campaigns')->everyMinute(); $schedule->command('mailcoach:send-campaign-mails')->everyMinute(); $schedule->command('mailcoach:run-automation-triggers')->everyMinute(); $schedule->command('mailcoach:run-automation-actions')->everyMinute(); $schedule->command('mailcoach:calculate-statistics')->everyMinute(); $schedule->command('mailcoach:calculate-automation-mail-statistics')->everyMinute(); $schedule->command('mailcoach:calculate-transactional-statistics')->everyMinute(); $schedule->command('mailcoach:send-campaign-summary-mail')->hourly(); $schedule->command('mailcoach:cleanup-processed-feedback')->hourly(); $schedule->command('mailcoach:send-email-list-summary-mail')->mondays()->at('9:00'); $schedule->command('mailcoach:delete-old-unconfirmed-subscribers')->daily(); $schedule->command('mailcoach:prune')->dailyAt('3:00'); } ``` -------------------------------- ### Send Campaign - PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Code examples for sending a campaign. The first method uses the `send()` method on an existing campaign object, assuming subject, HTML, and email list ID are already set. The second method, `sendTo()`, combines setting the email list and sending in one step. ```php $campaign->send(); // Alternatively you can set the email list and send the campaign in one go: $campaign->sendTo($emailList); ``` -------------------------------- ### Implement Custom Replacer for Mailcoach Automation Emails Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations This example shows how to create a custom replacer for Mailcoach automation emails. The `WebviewAutomationMailReplacer` class implements the `AutomationMailReplacer` interface, providing methods for help text and the actual text replacement logic using `str_ireplace`. ```php namespace Spatie\Mailcoach\Domain\Automation\Support\Replacers; use Spatie\Mailcoach\Domain\Automation\Models\AutomationMail; class WebviewAutomationMailReplacer implements AutomationMailReplacer { public function helpText(): array { return [ 'webviewUrl' => __mc('This URL will display the HTML of the automation email'), ]; } public function replace(string $text, AutomationMail $automationMail): string { $webviewUrl = $automationMail->webviewUrl(); return str_ireplace('::webviewUrl::', $webviewUrl, $text); } } ``` -------------------------------- ### Replace Mailcoach UI Routes with Mailcoach Macro Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading This code example demonstrates how to update route definitions in the RouteServiceProvider when migrating from Mailcoach UI to the integrated Mailcoach v6. It replaces the specific 'mailcoachUi' route macro with the general 'mailcoach' macro. ```php public function boot() { ... - Route::mailcoachUi('/'); + Route::mailcoach('/'); ... } ``` -------------------------------- ### Get First Email Opener Using Campaign Opens Relation Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Retrieves the email address of the first subscriber who opened a campaign using the 'opens' relation on the Campaign model. This provides insight into initial engagement. ```php $open = $campaign->opens->first(); $email = $open->subscriber->email; ``` -------------------------------- ### Configure Email Sending Throttling (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/advanced-usage-for-php-devs Configure email sending limits to comply with provider rate limits. This example shows how to set up throttling for 10 emails per second by adjusting `timespan_in_seconds` and `mails_per_timespan` in the `config/mail.php` file. ```php // config/mail.php 'mailers' => [ 'ses' => [ 'transport' => 'ses', // Throttling for 10 emails / second 'timespan_in_seconds' => 1, 'mails_per_timespan' => 10, ], ] ``` -------------------------------- ### Implement Custom Condition for Mailcoach Automation Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations This example demonstrates how to create a custom condition for Mailcoach's `ConditionAction`. The `HasTagCondition` class implements the `Condition` interface, defining methods for its name, description, validation rules, and the core checking logic. ```php namespace Spatie\Mailcoach\Domain\Automation\Support\Conditions; use Spatie\Mailcoach\Domain\Audience\Models\Subscriber; use Spatie\Mailcoach\Domain\Automation\Models\Automation; class HasTagCondition implements Condition { public function __construct( private Automation $automation, private Subscriber $subscriber, private array $data, ) { } public static function getName(): string { return (string) __mc('Has tag'); } public static function getDescription(array $data): string { return (string) __mc(':tag', ['tag' => $data['tag']]); } public static function rules(): array { return [ 'tag' => 'required', ]; } public function check(): bool { return $this->subscriber->hasTag($this->data['tag']); } } ``` -------------------------------- ### Send Test Automation Email in PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Provides examples for sending test versions of an automation email to single or multiple recipients. The `sendTestMail` method is used, accepting either a single email address string or an array of email addresses. Placeholders are not replaced in test emails. ```php // to a single email address $automationMail->sendTestMail('john@example.com'); ``` ```php // to multiple email addresses at once $automationMail->sentTestMail(['john@example.com', 'paul@example.com']) ``` -------------------------------- ### Get Campaign Name from BounceRegisteredEvent Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/advanced-usage-for-php-devs This snippet shows how to get the campaign name when a BounceRegisteredEvent occurs. It uses the `$send` property to access the associated campaign and its name. ```php $campaignName = $event->send->campaign->name; ``` -------------------------------- ### Get Automation Email Opens and Clicks (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Retrieves statistical data like opens and clicks for a specific automation email. It demonstrates accessing the 'opens' relation to get subscriber email addresses who opened the email. Dependencies include the Mailcoach library and PHP. ```PHP $open = $automationMail->opens->first(); $email = $open->subscriber->email; ``` -------------------------------- ### Get Subscriber Status Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Retrieves the current status of a subscriber. The status can be 'unconfirmed', 'subscribed', or 'unsubscribed'. ```php $subscriber->status; ``` -------------------------------- ### Publish Mailcoach Configuration - Command Line Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading Command to re-publish Mailcoach's configuration files to your application. This command forces the publication of the Mailcoach configuration, allowing you to easily update to the latest settings or re-apply your custom configurations after upgrading to v9. ```bash php artisan vendor:publish --tag=mailcoach-config --force ``` -------------------------------- ### Update Mailcoach Horizon Queue Configuration Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading This snippet shows the difference in the `queue` configuration for the `mailcoach-general` connection in `config/horizon.php`. The `mailcoach-schedule` queue has been added to ensure proper handling of scheduled tasks. ```diff 'mailcoach-general' => [ 'connection' => 'mailcoach-redis', - 'queue' => ['general', 'mailcoach', 'mailcoach-feedback', 'send-mail', 'send-automation-mail'], + 'queue' => ['general', 'mailcoach-schedule', 'mailcoach', 'mailcoach-feedback', 'send-mail', 'send-automation-mail'], 'balance' => 'auto', 'processes' => 10, 'tries' => 2, 'timeout' => 60 * 60, ], ``` -------------------------------- ### Create Automation Email in PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Demonstrates two methods for creating an automation email. The first uses a fluent builder pattern, while the second involves directly setting attributes on the AutomationMail model. Both require the AutomationMail class and a variable for HTML content. ```php AutomationMail::create() ->from('sender@example.com') ->subject('Welcome to Mailcoach') ->content($html); ``` ```php AutomationMail::create([ 'from_email' => 'sender@example.com', 'subject' => 'My newsletter #1', 'content' => $html, ]); ``` -------------------------------- ### Get Email from ComplaintRegisteredEvent Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/advanced-usage-for-php-devs This code shows how to extract the recipient's email address from a ComplaintRegisteredEvent. It navigates through the `$send` property to reach the subscriber's email. ```php $email = $event->send->subscription->subscriber->email; ``` -------------------------------- ### Get Email from BounceRegisteredEvent Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/advanced-usage-for-php-devs This code snippet demonstrates how to retrieve the email address associated with a BounceRegisteredEvent. It accesses the `$send` property of the event, then navigates to the subscriber's email. ```php $email = $event->send->subscriber->email; ``` -------------------------------- ### Livewire Component for Trigger Settings (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Create a Livewire component extending `AutomationTriggerComponent` to render the UI for trigger settings. This component provides access to the current automation and renders the necessary Blade view with input fields. ```php use Spatie\Mailcoach\Livewire\Automations\AutomationTriggerComponent; class DateTriggerComponent extends AutomationTriggerComponent { public function render() { return view('mailcoach::app.automations.components.triggers.dateTrigger'); } } ``` -------------------------------- ### Add Migration for Transactional Email Log and Tags Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading This migration adds a `mail_name` column and an index to the `mailcoach_transactional_mail_log_items` table, and a `description` column to the `mailcoach_tags` table. These changes are introduced in a new release of Mailcoach. ```php return new class extends Migration { public function up() { Schema::table('mailcoach_transactional_mail_log_items', function (Blueprint $table) { $table->string('mail_name')->nullable()->after('mailable_class'); $table->index(['mail_name', 'created_at'], 'mail_name_index'); }); Schema::table('mailcoach_tags', function (Blueprint $table) { $table->text('description')->nullable()->after('name'); }); } }; ``` -------------------------------- ### Get Subscriber Email for First Click on Campaign Link Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Demonstrates how to retrieve the email of a subscriber who clicked a specific campaign link for the first time. It utilizes relations on both CampaignLink and CampaignClick models. ```php $campaignLink = $campaign->links->first(); $campaignClick = $campaignLink->links->first(); $email = $campaingClick->subscriber->email; ``` -------------------------------- ### Get Campaign Webview URL in PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Shows how to retrieve the unique URL for a campaign's webview. This URL allows recipients to view the campaign content in a browser, even if they didn't originally subscribe. ```php $campaign->webViewUrl(); ``` -------------------------------- ### Create a Livewire Action Component for Mailcoach Automations (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Defines a Livewire component to create custom actions within Mailcoach automations. It extends `AutomationActionComponent` and handles data retrieval, validation rules, and rendering a Blade view. Dependencies include `SpatieMailcoachDomainAutomationSupportLivewireAutomationActionComponent` and `IlluminateValidationRule`. ```php use Spatie\Mailcoach\Livewire\Automations\AutomationActionComponent; use Illuminate\Validation\Rule; class WaitActionComponent extends AutomationActionComponent { public string $length = '1'; public string $unit = 'days'; public array $units = [ 'minutes' => 'Minute', 'hours' => 'Hour', 'days' => 'Day', 'weeks' => 'Week', 'weekdays' => 'Weekdays', 'months' => 'Month', ]; public function getData(): array { return [ 'length' => (int) $this->length, 'unit' => $this->unit, ]; } public function rules(): array { return [ 'length' => ['required', 'integer', 'min:1'], 'unit' => ['required', Rule::in([ 'minutes', 'hours', 'days', 'weeks', 'weekdays', 'months', ])], ]; } public function render() { return view('mailcoach::app.automations.components.actions.waitAction'); } } ``` -------------------------------- ### Configure Unlayer Editor and Image Uploads in Mailcoach Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/choosing-an-editor Configure Mailcoach to use the Unlayer editor and set up image upload parameters. This includes defining the disk name and maximum dimensions for uploaded images. Unlayer is a WYSIWYG editor requiring no HTML knowledge. ```php config(['mailcoach.editor' => \Spatie\MailcoachUnlayer\UnlayerEditor::class]); config(['mailcoach.unlayer' => [ 'disk_name' => env('MAILCOACH_UPLOAD_DISK', 'public'), 'max_width' => 1500, 'max_height' => 1500, ]]); ``` -------------------------------- ### Publish Mailcoach Views - Command Line Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading Command to re-publish Mailcoach's view files to your application. This command forces the publication of the Mailcoach views, enabling you to update to the latest templates or re-apply any customizations you've made after upgrading to v9. ```bash php artisan vendor:publish --tag=mailcoach-views --force ``` -------------------------------- ### PHP Get Automation Email Webview URL Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations This snippet demonstrates how to retrieve the webview URL for an automation email. The webview URL provides an alternative way for recipients to view email content, especially useful for those who may not have directly subscribed. ```php $automationMail->webViewUrl(); ``` -------------------------------- ### Get Automation Email Link Clicks (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Fetches click statistics for links within an automation email. It shows how to access the 'links' relation on an AutomationMailLink to retrieve subscriber emails who clicked a specific link. Requires Mailcoach and PHP. ```PHP $automationMailLink = $automationMail->links->first(); $automationMailClick = $automationMailLink->links->first(); $email = $automationMailClick->subscriber->email; ``` -------------------------------- ### Define Trigger Settings Fields and Validation (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Add UI configuration and validation for custom triggers. Use `getComponent` to specify a Livewire component for the UI, `make` to process input data, and `rules` to define validation rules for trigger settings. ```php use Spatie\Mailcoach\Domain\Automation\Models\AutomationTrigger; use Spatie\Mailcoach\Domain\Automation\Support\Triggers\TriggeredBySchedule; use Spatie\Mailcoach\Domain\Automation\Support\Rules\DateTimeFieldRule; class DateTrigger extends AutomationTrigger implements TriggeredBySchedule { public CarbonInterface $date; public function __construct(CarbonInterface $date) { parent::__construct(); $this->date = $date; } public static function getComponent(): ?string { return 'date-trigger'; } public static function make(array $data): self { return new self((new DateTimeFieldRule())->parseDateTime($data['date'])); } public static function rules(): array { return [ 'date' => ['required', new DateTimeFieldRule()], ]; } public function trigger(Automation $automation): void { if (! now()->startOfMinute()->equalTo($this->date->startOfMinute())) { return; } $this->runAutomation($automation->newSubscribersQuery()); } } ``` -------------------------------- ### Create Subscriber with Attributes and Subscribe Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Creates a subscriber with a specific email and attributes (like first and last name), then subscribes them to a list. This is a comprehensive way to add new subscribers. ```php Subscriber::createWithEmail('john@example.com') ->withAttributes([ 'first_name' => 'John', 'last_name' => 'Doe' ]) ->subscribeTo($emailList); ``` -------------------------------- ### PHP Create Automation with Instantiated Segment Object Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations This PHP code demonstrates creating an automation and applying a custom segment using an instantiated segment object. This allows for dynamic configuration of segments at runtime, such as specifying the character to filter email addresses by. ```php Automation::create() ->segment(new OnlyEmailAddressesStartingWith('b')); ``` -------------------------------- ### Configure Editor.js in Mailcoach Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/choosing-an-editor Configure Mailcoach to use the Editor.js block-based WYSIWYG editor for campaigns and automations. This also includes instructions on publishing the configuration file and setting up image uploads. ```php config(['mailcoach.campaign.editor' => \Spatie\MailcoachEditor\Editor::class]); config(['mailcoach.automationMail.editor' => \Spatie\MailcoachEditor\Editor::class]); ``` ```bash php artisan vendor:publish --provider="Spatie\MailcoachEditor\MailcoachEditorServiceProvider" --tag="mailcoach-editor-config" ``` -------------------------------- ### Update Mailcoach Config for v8 Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading This diff shows the changes in Mailcoach's configuration file for version 8. It highlights the removal of `TextAreaEditorComponent` and the introduction of new editor classes for content and templates. ```diff {-'content_editor' => \Spatie\Mailcoach\Livewire\Editor\TextAreaEditorComponent::class,-} {+'content_editor' => \Spatie\Mailcoach\Domain\Editor\Markdown\Editor::class,+} {-'template_editor' => \Spatie\Mailcoach\Livewire\Editor\TextAreaEditorComponent::class,-} {+'template_editor' => \Spatie\Mailcoach\Domain\Editor\Codemirror\Editor::class,+} ``` -------------------------------- ### Get All Subscribers of an Email List Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Retrieves all subscribers from an email list. This method only returns subscribers with a 'subscribed' status. To include unconfirmed or unsubscribed users, use `allSubscribers`. Access a subscriber's email address using the `email` property. ```php $subscribers = $emailList->subscribers; // returns all subscribers $email = $subscribers->first()->email; $allSubscribers = $emailList->allSubscribers; // includes unconfirmed and unsubscribed ``` -------------------------------- ### Create Custom Segment - Configurable Character Match in PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Implements a custom segment class that filters subscribers based on a configurable starting character in their email address. The character is passed during instantiation, and the `shouldSend` method uses this character for filtering. This allows for more flexible segmentation. ```php use Spatie\Mailcoach\Domain\Subscriber\Models\Subscriber; use Spatie\Mailcoach\Support\Segments\Segment; use Illuminate\Support\Str; class OnlyEmailAddressesStartingWith extends Segment { public string $character; public function __construct(string $character) { $this->character = $character; } public function shouldSend(Subscriber $subscriber): bool { return Str::startsWith($subscriber->email, $this->character); } } ``` ```php Campaign::create() ->content($yourHtml) ->segment(new OnlyEmailAddressesStartingWith('b')) ->sendTo($emailList); ``` -------------------------------- ### Update Mailcoach Scheduled Commands in Kernel.php Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading This snippet shows the updated schedule method in `app/Console/Kernel.php` for Mailcoach v9. It lists various commands and their execution intervals (e.g., `everyMinute`, `hourly`, `daily`). Methods like `runInBackground()` and `withoutOverlapping()` are no longer needed due to internal job dispatching. ```php protected function schedule(Schedule $schedule) { $schedule->command('mailcoach:send-automation-mails')->everyMinute(); $schedule->command('mailcoach:send-scheduled-campaigns')->everyMinute(); $schedule->command('mailcoach:send-campaign-mails')->everyMinute(); $schedule->command('mailcoach:run-automation-triggers')->everyMinute(); $schedule->command('mailcoach:run-automation-actions')->everyMinute(); $schedule->command('mailcoach:calculate-statistics')->everyMinute(); $schedule->command('mailcoach:calculate-automation-mail-statistics')->everyMinute(); $schedule->command('mailcoach:send-campaign-summary-mail')->hourly(); $schedule->command('mailcoach:cleanup-processed-feedback')->hourly(); $schedule->command('mailcoach:send-email-list-summary-mail')->mondays()->at('9:00'); $schedule->command('mailcoach:delete-old-unconfirmed-subscribers')->daily(); } ``` -------------------------------- ### Manage Subscriber Extra Attributes (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Provides PHP examples for interacting with extra attributes associated with a Mailcoach subscriber. This includes retrieving all attributes, updating a single attribute, replacing all attributes at once, and filtering subscribers based on their extra attributes. ```php $subscriber = $subscription->subscriber; // get all extra attributes $subscriber->extra_attributes->all(); // return an array with all extra attributes; // updating an extra attibute $subscriber->extra_attributes->first_name = 'Other name'; $subscriber->save(); // replacing all extra attributes in one go $subscriber->extra_attributes = ['first_name' => 'Jane', 'last_name' => 'Dane']; $subscriber->save(); // returns all models with a first_name set to John $subscriber->withExtraAttributes(['first_name' => 'John'])->get(); ``` -------------------------------- ### Set Campaign Content and Placeholders - PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns This code illustrates how to set the HTML content for a campaign's content item and save it. It highlights the use of placeholders like `{{ unsubscribeUrl }}`, `{{ unsubscribeTag['your tag'] }}`, and `{{ webviewUrl }}` which are automatically replaced when the campaign is sent. ```php $campaign->contentItem->html = $yourHtml; $campaign->contentItem->save(); ``` -------------------------------- ### Create and Save a Campaign - PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns This snippet demonstrates how to programmatically create a new campaign using the Campaign::create() method. It includes setting the sender's email, associating it with an email list, naming the campaign, and defining its subject and HTML content. ```php $campaign = Campaign::create() ->from('sender@example.com') ->to($emailList); $campaign->name = 'My newsletter #1'; $campaign->save(); $campaign->contentItem->subject = 'Newsletter #1'; $campaign->contentItem->html = $html; $campaign->contentItem->save(); ``` -------------------------------- ### Attach Tags to Form Subscriptions Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Attaches specified tags to a subscriber during form submission by using a hidden input field named 'tags'. Only tags configured in the `allowedFormSubscriptionTags` relation of the email list will be attached. Example shows how to set these allowed tags programmatically. ```html ``` ```php $tagA = $emailList->tags()->where('name', 'tagA')->first(); $tagB = $emailList->tags()->where('name', 'tagB')->first(); $emailList->allowedFormSubscriptionTags([$tagA->id, $tagB->id]); ``` -------------------------------- ### Enable Double Opt-in - PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Illustrates how to create a new email list with the double opt-in feature enabled. When `requires_confirmation` is set to true, new subscribers will receive a confirmation email before their subscription is activated. ```php EmailList::create([ 'name' => 'My list', 'requires_confirmation' => true, ]); ``` -------------------------------- ### Publish Mailcoach Views Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Publishes Mailcoach's view files to the resources directory, allowing for customization of landing pages and email templates. This is a prerequisite for modifying default Mailcoach responses. ```bash php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-views" ``` -------------------------------- ### Set From Name and Reply To for Automation Email in PHP Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Illustrates how to specify a 'from' name as a second parameter to the `from` method and how to set 'reply-to' email and name using the `replyTo` method when creating an automation email. These methods enhance sender identification. ```php AutomationMail::create()->from('sender@example.com', 'Sender name') ``` ```php AutomationMail::create()->replyTo('john@example.com', 'John Doe') ``` -------------------------------- ### Create Event-Based Trigger (PHP) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Implement an event-based trigger by extending `AutomationTrigger` and the `TriggeredByEvents` interface. The `subscribe` method listens for specific application events (e.g., `SubscribedEvent`) and runs the automation for relevant subscribers. ```php use Spatie\Mailcoach\Domain\Audience\Events\SubscribedEvent; use Spatie\Mailcoach\Domain\Automation\Support\Triggers\TriggeredByEvents; use Spatie\Mailcoach\Domain\Automation\Models\AutomationTrigger; class SubscribedTrigger extends AutomationTrigger implements TriggeredByEvents { public static function getName(): string { return (string) __mc('When a user subscribes'); } public function subscribe($events): void { $events->listen( SubscribedEvent::class, function ($event) { $this->runAutomation($event->subscriber); } ); } } ``` -------------------------------- ### Sending Automation Email Action Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/automations Demonstrates the 'run' method for sending an automation email to a subscriber. This is a core function within the SendAutomationMailAction. ```php public function run(Subscriber $subscriber): void { $this->automationMail->send($subscriber); } ``` -------------------------------- ### Define Mailcoach UI Authorization Gate in Laravel Source: https://www.mailcoach.app/self-hosted/documentation/v9/getting-started/installation/in-an-existing-laravel-app This PHP snippet demonstrates how to define a gate named 'viewMailcoach' in a Laravel service provider. This gate determines which users have permission to access the Mailcoach UI, typically by checking a user attribute like 'admin'. It ensures only authorized users can interact with the Mailcoach interface. ```php // in a service provider public function boot() { \Illuminate\Support\Facades\Gate::define('viewMailcoach', function ($user = null) { return optional($user)->admin; }); } ``` -------------------------------- ### Use Mailcoach Template in Mailable (`content` method) Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/transactional-emails This example shows how to integrate a Mailcoach transactional email template into a Mailable class using the `UsesMailcoachTemplate` trait. The `template()` method is called within the `content` method, referencing the template by its name. The mailable will then use the subject and body defined in the specified template. ```php use Spatie\Mailcoach\Domain\TransactionalMail\Mails\Concerns\UsesMailcoachTemplate use Illuminate\Mail\Mailable use Illuminate\Mail\Mailables\Content; class YourMailable extends Mailable { use UsesMailcoachTemplate; public function content(): Content { $this->template('test-template'); // return content; } } ``` -------------------------------- ### Configure and Embed Subscription Form Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/audience Enables form submissions for an email list by setting `allow_form_subscriptions` to true. Provides an HTML form example for embedding on external sites, including fields for email, name, redirects, and optional tag handling. Ensure double opt-in settings are considered for pending subscriptions. ```php $emailList->update(['allow_form_subscriptions' => true]); ``` ```html
``` -------------------------------- ### Clear Icon and View Cache with Artisan Source: https://www.mailcoach.app/self-hosted/documentation/v9/other/upgrading These Artisan commands are used to clear the application's icon cache and view cache. This is often necessary after upgrades to ensure the latest assets and views are loaded. ```bash php artisan icon:clear php artisan view:clear ``` -------------------------------- ### Publish Mailcoach Views Source: https://www.mailcoach.app/self-hosted/documentation/v9/features/campaigns Provides the Artisan command to publish Mailcoach's view files, enabling customization of the webview and other email templates. This command specifically targets the views related to campaign functionality. ```bash php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-views" ```