VOOZH about

URL: https://deepwiki.com/hypervel/mail/5-working-with-mailables

⇱ Working with Mailables | hypervel/mail | DeepWiki


Loading...
Menu

Working with Mailables

This document provides a comprehensive guide to creating, configuring, and sending emails using the Mailable class. It covers the core Mailable abstraction, its lifecycle, content configuration, recipient management, and dispatch patterns (both synchronous and asynchronous).

For detailed information about specific aspects:

  • Creating custom mailable classes with the build() method, see page 5.1
  • The mailable preparation pipeline and hydration process, see page 5.2
  • Working with file attachments, see page 5.3
  • Using the fluent PendingMail interface, see page 5.4

Mailable Class Overview

The Mailable class src/Mailable.php42 serves as the primary abstraction for email messages. It implements Hypervel\Mail\Contracts\Mailable src/Contracts/Mailable.php12 and Hypervel\Support\Contracts\Renderable, providing a fluent API for email configuration and dispatch.


Sources: src/Mailable.php42-1518 src/Contracts/Mailable.php12-53

Mailable Lifecycle and Preparation

When a mailable is dispatched, it follows a well-defined preparation pipeline that hydrates the message from various methods before sending.


Sources: src/Mailable.php163-182 src/Mailable.php1340-1471

The preparation occurs in prepareMailableForDelivery() src/Mailable.php1340-1353 and follows this order:

  1. Build Phase: Calls the optional build() method if it exists src/Mailable.php1342-1347
  2. Headers Hydration: Calls headers() method via ensureHeadersAreHydrated() and sets Message-Id, References, and custom headers src/Mailable.php1349 src/Mailable.php1358-1379
  3. Envelope Hydration: Calls envelope() method via ensureEnvelopeIsHydrated() and sets recipients, subject, tags, metadata src/Mailable.php1350 src/Mailable.php1384-1417
  4. Content Hydration: Calls content() method via ensureContentIsHydrated() and sets view, html, text, markdown templates src/Mailable.php1351 src/Mailable.php1422-1453
  5. Attachments Hydration: Calls attachments() method via ensureAttachmentsAreHydrated() and adds file attachments src/Mailable.php1352 src/Mailable.php1458-1471

Creating and Configuring Mailable Instances

Mailable instances can be created directly and configured using either property assignment or method chaining.

Direct Property Configuration

The Mailable class exposes several public properties that can be set directly:

PropertyTypeLineDescription
$toarray61Primary recipients
$ccarray66Carbon copy recipients
$bccarray71Blind carbon copy recipients
$fromarray56Sender address
$replyToarray76Reply-to addresses
$subjectstring81Email subject line
$viewstring96Blade view template
$markdownstring86Markdown template
$textViewstring101Plain text view template
$viewDataarray106Data to pass to views
$attachmentsarray111File path attachments
$rawAttachmentsarray116In-memory data attachments
$diskAttachmentsarray121Storage disk attachments
$localestring51Message locale
$mailer?string146Mailer name to use
$theme?string141Markdown theme

Sources: src/Mailable.php51-146

Fluent Method Configuration

The Mailable class provides fluent methods for configuration:

Method CategoryMethod SignatureLine
Recipientsto(array|object|string $address, ?string $name = null): static529
cc(array|object|string $address, ?string $name = null): static549
bcc(array|object|string $address, ?string $name = null): static565
from(array|object|string $address, ?string $name = null): static513
replyTo(array|object|string $address, ?string $name = null): static581
Contentsubject(string $subject): static717
view(string $view, array $data = []): static747
markdown(string $view, array $data = []): static736
html(string $html): static758
text(string $textView, array $data = []): static768
with(array|string $key, mixed $value = null): static779
Attachmentsattach(Attachable|Attachment|string $file, array $options = []): static793
attachMany(array $files): static814
attachData(string $data, string $name, array $options = []): static929
attachFromStorage(string $path, ?string $name = null, array $options = []): static883
attachFromStorageDisk(?string $disk, string $path, ?string $name = null, array $options = []): static891
Metadatatag(string $value): static955
metadata(string $key, string $value): static974
locale(string $locale): static487
priority(int $level = 3): static501
mailer(?string $mailer): static1476

Sources: src/Mailable.php487-1481

Address Normalization

Recipient methods accept flexible input formats:

  • String: "user@example.com"
  • String with name: to("user@example.com", "John Doe")
  • Array: ["email" => "user@example.com", "name" => "John Doe"]
  • Object: Any object with email property (and optional name property)
  • Symfony Address: Symfony\Component\Mime\Address instance
  • Mailables Address: Hypervel\Mail\Mailables\Address instance
  • Collection: Collection of any of the above

All recipients are normalized to [['address' => string, 'name' => ?string]] format internally via setAddress() src/Mailable.php599-622 and deduplicated by address src/Mailable.php614-619

Sources: src/Mailable.php513-663

Sending Emails

Synchronous Sending

The send() method dispatches the email immediately:


The method accepts either a Factory (MailManager) or Mailer instance. When a Factory is provided, it resolves the mailer by the name specified in $this->mailer property src/Mailable.php168-170

The send process:

  1. Applies locale context via withLocale() src/Mailable.php165
  2. Prepares the mailable via prepareMailableForDelivery() src/Mailable.php166
  3. Builds the view structure via buildView() src/Mailable.php172
  4. Builds view data via buildViewData() src/Mailable.php172
  5. Invokes the mailer with a callback that configures the message src/Mailable.php172-180

The callback builds the message by calling:

Sources: src/Mailable.php163-182

Asynchronous Sending (Queued)

The queue() and later() methods dispatch emails asynchronously via the queue system:


Queue Process:

  1. Creates a SendQueuedMailable job via newQueuedJob() src/Mailable.php199 src/Mailable.php215
  2. Applies middleware if the mailable defines middleware() method or $middleware property src/Mailable.php226-229
  3. Pushes the job to the specified connection and queue src/Mailable.php197-200 src/Mailable.php212-216

The mailable can specify connection and queue via properties:

Sources: src/Mailable.php186-230

Rendering Without Sending

The render() method builds the email HTML without sending:


This is useful for:

  • Testing email appearance
  • Generating HTML for preview
  • Debugging template issues

The render process mirrors send() but only returns the HTML content src/Mailable.php237-249

Sources: src/Mailable.php237-249

Content Configuration

The Mailable class supports multiple content types, resolved in priority order during buildView().

Content Type Priority


Sources: src/Mailable.php256-281

HTML Content

Set raw HTML content using the html() method:


When $html property is set, it's wrapped in HtmlString and returned with optional plain text view src/Mailable.php258-263

Sources: src/Mailable.php755-760

Markdown Content

Set Markdown template using the markdown() method:


Markdown views are processed through buildMarkdownView() which:

  1. Builds HTML via buildMarkdownHtml() using Markdown renderer src/Mailable.php293
  2. Builds text via buildMarkdownText() or uses $textView if set src/Mailable.php294

The renderer respects the $theme property or defaults to config value src/Mailable.php354-363

Sources: src/Mailable.php732-739 src/Mailable.php288-363

Blade Views

Set Blade templates using the view() and text() methods:


Multiple view combinations are supported:

Sources: src/Mailable.php744-771

View Data

View data is passed to templates via the with() method or $viewData property:


The buildViewData() method constructs the final data array by merging:

  1. Explicit $viewData property src/Mailable.php305
  2. Global view data callback if set via buildViewDataUsing() src/Mailable.php307-309
  3. All public properties from the mailable instance (excluding Mailable base class properties) src/Mailable.php311-315

This allows passing data via public properties without explicit with() calls.

Sources: src/Mailable.php776-785 src/Mailable.php303-318

Dynamic View Data Methods

The Mailable class provides magic method handling for dynamic view data:


Any method starting with "with" followed by camelCase name is converted to view data src/Mailable.php1509-1510

Sources: src/Mailable.php1499-1514

Recipient Management

Recipients are stored as normalized arrays with deduplication by address src/Mailable.php615-620

Setting Recipients

Each recipient method accepts flexible formats and ensures uniqueness:


Sources: src/Mailable.php530-593

Checking Recipients

Query methods verify recipient presence:


These methods check both properties and envelope method definitions src/Mailable.php669-709

Sources: src/Mailable.php522-593 src/Mailable.php669-709

Automatic Subject Generation

If no subject is set, the buildSubject() method generates one from the class name:


Class name is converted to title case with spaces src/Mailable.php394-402

Sources: src/Mailable.php394-403

Locale-Aware Sending

The locale() method sets the message locale:


If a recipient implements HasLocalePreference, their preferred locale is automatically applied src/Mailable.php532-534

The locale context wraps the entire send/render operation via withLocale() src/Mailable.php165 src/Mailable.php239

Sources: src/Mailable.php488-493 src/Mailable.php532-534

Tags and Metadata

Tags and metadata are transport-specific headers for categorizing and tracking emails.

Tags

Tags are string labels added via the tag() method:


Tags are added as Symfony\Component\Mailer\Header\TagHeader instances during message building src/Mailable.php448-456

Sources: src/Mailable.php952-966

Metadata

Metadata are key-value pairs added via the metadata() method:


Metadata is added as Symfony\Component\Mailer\Header\MetadataHeader instances src/Mailable.php462-470

Sources: src/Mailable.php971-985

Both tags and metadata can be defined in the envelope() method as well src/Mailable.php1403-1409

Advanced Features

Priority

Set message priority (1=highest, 5=lowest):


Priority is set via a Symfony message callback src/Mailable.php502-508

Sources: src/Mailable.php495-509

Custom Mailer Selection

Specify which mailer configuration to use:


This is resolved during send() when a Factory is provided src/Mailable.php168-170

Sources: src/Mailable.php1473-1478

Symfony Message Callbacks

Register callbacks that receive the underlying Symfony message:


Callbacks are executed after all other message configuration src/Mailable.php476-482

Sources: src/Mailable.php1483-1488

Global View Data Callback

Register a global callback for view data:


This callback receives the mailable instance and returns additional view data merged into all mailables src/Mailable.php307-309

Sources: src/Mailable.php1493-1496

Testing Mailables

The Mailable class provides comprehensive assertion methods for testing without sending emails.

Assertion Methods

MethodPurpose
assertFrom($address, $name)Assert sender address
assertTo($address, $name)Assert primary recipient
assertHasTo($address, $name)Alias for assertTo()
assertHasCc($address, $name)Assert CC recipient
assertHasBcc($address, $name)Assert BCC recipient
assertHasReplyTo($address, $name)Assert reply-to address
assertHasSubject($subject)Assert subject line
assertSeeInHtml($string, $escape)Assert text in HTML body
assertDontSeeInHtml($string, $escape)Assert text not in HTML body
assertSeeInOrderInHtml($strings, $escape)Assert ordered text in HTML body
assertSeeInText($string)Assert text in plain-text body
assertDontSeeInText($string)Assert text not in plain-text body
assertSeeInOrderInText($strings)Assert ordered text in plain-text body
assertHasAttachment($file, $options)Assert file attachment
assertHasAttachedData($data, $name, $options)Assert data attachment
assertHasAttachmentFromStorage($path, $name, $options)Assert storage attachment
assertHasAttachmentFromStorageDisk($disk, $path, $name, $options)Assert disk attachment
assertHasTag($tag)Assert tag presence
assertHasMetadata($key, $value)Assert metadata presence

All assertion methods call renderForAssertions() which renders the email once and caches the result src/Mailable.php1300-1332

Sources: src/Mailable.php989-1293

Content Assertions

Content assertions work with escaped or raw HTML:


Sources: src/Mailable.php1114-1203

Rendering for Assertions

The renderForAssertions() method src/Mailable.php1303-1334 prepares both HTML and plain-text versions:

  1. Applies locale context via withLocale() src/Mailable.php1309
  2. Prepares the mailable via prepareMailableForDelivery() src/Mailable.php1310
  3. Renders HTML view via Mailer::render() src/Mailable.php1312-1317
  4. Extracts text view from array src/Mailable.php1319-1323 or renders separately src/Mailable.php1326-1331
  5. Caches results in $assertionableRenderStrings property src/Mailable.php1309

Returns [string $html, string $text] array src/Mailable.php1333

Sources: src/Mailable.php1303-1334

Class Traits and Capabilities

The Mailable class uses several traits src/Mailable.php44-46 for extended functionality:

TraitNamespaceCapabilities
ConditionableHyperf\ConditionableProvides when() and unless() methods for conditional configuration
ForwardsCallsHyperf\Support\TraitsEnables method forwarding to other objects
LocalizableHypervel\Support\TraitsProvides withLocale() for locale context management
MacroableHyperf\MacroableAllows extending the class with custom methods via macros

The Macroable trait is aliased to avoid conflicts with ForwardsCalls::__call() src/Mailable.php44-46

Sources: src/Mailable.php44-46

Property Storage Format

Recipients and attachments use specific internal formats:

Recipient Format


Attachment Formats


Sources: src/Mailable.php609-612 src/Mailable.php800-803 src/Mailable.php928-932 src/Mailable.php890-897

Refresh this wiki

On this page