VOOZH about

URL: https://deepwiki.com/hypervel/mail/4.2-mailer-component

⇱ Mailer Component | hypervel/mail | DeepWiki


Loading...
Menu

Mailer Component

Purpose and Scope

The Mailer class is the central component responsible for sending emails in the hypervel/mail package. It provides the primary interface for dispatching messages, rendering views, managing global addressing, and integrating with the transport layer. This page documents the Mailer class structure, its methods for sending emails, view rendering capabilities, and integration with events and queues.

For information about creating Mailer instances and transport configuration, see Mail Manager and Factory Pattern. For details on creating mailable classes, see Creating Mailable Classes. For the fluent interface used to configure recipients, see Fluent Mail Interface.

Class Overview

The Mailer class implements two contracts: MailerContract and MailQueueContract, providing both synchronous and asynchronous email sending capabilities. It serves as the bridge between application code, the view rendering system, and the transport layer.


Mailer Class Structure and Interfaces

Sources: src/Mailer.php33-76

Dependencies and Constructor

The Mailer constructor requires four dependencies that define its capabilities:

ParameterTypePurpose
$namestringIdentifies this mailer instance (used for configuration reference)
$viewsFactoryInterfaceProvides view rendering capabilities via Hyperf's view engine
$transportTransportInterfaceHandles actual message transmission (Symfony Mailer transport)
$eventsEventDispatcherInterface (optional)Enables event dispatching for lifecycle hooks

The $name parameter allows the mailer to identify itself in queued jobs and configuration contexts. The $views dependency provides access to Blade templates and Markdown rendering. The $transport handles the low-level protocol communication (SMTP, API calls, etc.). The optional $events dispatcher enables MessageSending and MessageSent event hooks.


Mailer Dependency Injection Flow

The QueueFactory is set separately via setQueue() method rather than through the constructor, allowing the mailer to function without queue capabilities if needed.

Sources: src/Mailer.php70-76 src/Mailer.php512-517

Global Addressing Configuration

The Mailer class supports four types of global addressing that apply to all messages sent through the instance:

Global From Address

The alwaysFrom() method sets a default sender address applied to every message:


This is useful for ensuring consistent branding. If set, every Message instance created by createMessage() will automatically include this from address.

Global To Address (Testing Override)

The alwaysTo() method redirects all outbound messages to a specific address:


When configured, this overrides all recipient addresses and removes CC/BCC recipients. This is primarily used for testing and local development to prevent accidental email delivery to real users.

Global Reply-To Address

The alwaysReplyTo() method sets a default reply-to address:


Responses to emails will be directed to this address instead of the from address.

Global Return Path

The alwaysReturnPath() method sets the return path for bounce handling:


Bounced messages will be sent to this address for processing.

MethodStorage PropertyApplied ByPurpose
alwaysFrom()$this->fromcreateMessage() line 432Default sender
alwaysTo()$this->tosetGlobalToAndRemoveCcAndBcc() line 242Testing override
alwaysReplyTo()$this->replyTocreateMessage() line 439Reply address
alwaysReturnPath()$this->returnPathcreateMessage() line 443Bounce handling

Sources: src/Mailer.php38-108 src/Mailer.php425-448 src/Mailer.php349-359

Creating PendingMail Instances

The Mailer provides three methods that create PendingMail instances for fluent recipient configuration:

to() Method


Creates a PendingMail instance with the specified recipient(s). If both $users and $name are strings, they are wrapped in an Address object.

cc() Method


Creates a PendingMail instance with CC recipients.

bcc() Method


Creates a PendingMail instance with BCC recipients.


PendingMail Creation Flow

These methods enable the fluent syntax: Mail::to($user)->cc($others)->send($mailable). The PendingMail class accumulates recipient configuration before delegating to Mailer::send().

Sources: src/Mailer.php113-144

Sending Methods

The Mailer class provides multiple methods for sending emails, each optimized for different use cases.

Primary Send Method

The send() method is the primary email dispatch mechanism:


The method accepts three parameter types:

  1. Mailable instance: Delegates to sendMailable() which handles the mailable lifecycle
  2. View string/array: Renders the view with provided data
  3. Array with keys: ['html' => ..., 'text' => ..., 'raw' => ...] for explicit content types

Send Method Decision Flow

Sources: src/Mailer.php215-264

Sending Mailables

The sendMailable() method handles Mailable instances:


This method checks if the mailable implements ShouldQueue. If so, it queues the mailable; otherwise, it sends immediately. The mailable's mailer() method sets the mailer name for configuration context.

Sources: src/Mailer.php269-274

Simple Content Methods

Three convenience methods handle simple message types:

html() Method


Sends HTML content directly without view rendering. The HTML is wrapped in a HtmlString and passed to send().

raw() Method


Sends plain text content without view rendering.

plain() Method


Renders a view as plain text only (no HTML part).

MethodContent TypeView RenderingUse Case
html()HTML onlyNoPre-rendered HTML strings
raw()Text onlyNoSimple text messages
plain()Text onlyYesPlain text templates
send()HTML + TextYesFull featured emails

Sources: src/Mailer.php149-168

Synchronous Sending

The sendNow() method forces immediate synchronous sending:


This bypasses the queue even if the mailable implements ShouldQueue. It's useful for critical notifications that must be sent immediately.

Sources: src/Mailer.php279-284

View Rendering

The Mailer class provides comprehensive view rendering capabilities that integrate with Hyperf's view engine.

Render Method

The render() method generates HTML from a view without sending:


This is useful for previewing email content or testing templates. The method:

  1. Parses the view specification into HTML, plain, and raw components
  2. Creates a temporary Message instance and adds it to $data['message']
  3. Renders the view
  4. Replaces embedded attachment references with inline data URIs

Sources: src/Mailer.php173-186

View Parsing

The parseView() method normalizes different view specification formats:


Returns [$htmlView, $plainView, $rawText] array supporting three input formats:

  1. String: 'emails.welcome'['emails.welcome', null, null]
  2. Numeric array: ['emails.welcome', 'emails.welcome-plain'][$view[0], $view[1], null]
  3. Associative array: ['html' => '...', 'text' => '...', 'raw' => '...'] → extracts each key

Sources: src/Mailer.php291-316

Content Addition

The addContent() method applies rendered content to a Message:


This method:

  • Renders HTML view via renderView() if provided
  • Renders plain text view if provided
  • Sets raw text directly if provided
  • Ensures at least one space character if content is empty (prevents transport errors)

Sources: src/Mailer.php321-334

View Rendering Pipeline

The renderView() method handles actual template rendering:


This supports three view types:

  1. Closure: Evaluated with $data parameter
  2. Htmlable: Calls toHtml() method directly
  3. String: Delegates to view factory for Blade/Markdown rendering

Sources: src/Mailer.php339-346

Embedded Attachments

The replaceEmbeddedAttachments() method converts cid: references to data URIs:


This enables email preview in browsers by replacing content ID references (e.g., cid:logo.png) with base64-encoded data URIs (e.g., data:image/png;base64,...). The method scans for <img src="cid:..."> tags and replaces them with inline data.

Sources: src/Mailer.php191-210

Queue Integration

The Mailer class provides methods for asynchronous email sending via the queue system.

Queue Method


Queues a mailable for later sending. This method only accepts MailableContract instances and throws InvalidArgumentException for other types. If $queue is specified, it calls the mailable's onQueue() method to set the queue name.

Later Method


Queues a mailable with a delay. The $delay can be:

  • Integer: Seconds from now
  • DateInterval: Relative time period
  • DateTimeInterface: Absolute timestamp

Queue-Specific Variants

MethodPurpose
queue($view, $queue)Queue on default or specified queue
onQueue($queue, $view)Alias for queue with swapped parameters
queueOn($queue, $view)Alternative alias matching framework conventions
later($delay, $view, $queue)Queue with delay
laterOn($queue, $delay, $view)Queue on specific queue with delay

Queue Integration Flow

The queue integration requires a QueueFactory to be set via setQueue(). The actual queuing logic is delegated to the mailable, which creates a SendQueuedMailable job (see Queue Integration).

Sources: src/Mailer.php366-420 src/Mailer.php512-517

Event Integration

The Mailer class integrates with PSR-14 event dispatching to enable lifecycle hooks.

MessageSending Event

The shouldSendMessage() method dispatches a MessageSending event before transmission:


Listeners can prevent sending by calling $event->shouldNotSend() on the event object. If no event dispatcher is configured, sending always proceeds.

Sources: src/Mailer.php464-473

MessageSent Event

The dispatchSentEvent() method fires after successful transmission:


This event includes the SentMessage wrapper containing the Symfony SentMessage and provides $data context from the send operation.

Sources: src/Mailer.php478-483

Event Flow in Send Operation


Event Lifecycle in Mailer

The event system enables:

  • Logging: Record all outbound messages
  • Testing: Capture messages without sending
  • Rate limiting: Prevent sending based on external conditions
  • Modification: Alter messages before transmission (via MessageSending)
  • Tracking: Record sent messages (via MessageSent)

For detailed event information, see Event System.

Sources: src/Mailer.php464-483

Message Creation and Lifecycle

Message Instance Creation

The createMessage() method creates new Message instances:


The Message class wraps Symfony's Email object and provides a fluent interface for message configuration. Global addressing is applied automatically during creation.

Sources: src/Mailer.php425-448

Global To Override

When alwaysTo() is configured, the setGlobalToAndRemoveCcAndBcc() method redirects all messages:


This method:

  1. Removes all original recipients
  2. Sets the global to address
  3. Removes all CC recipients
  4. Removes all BCC recipients

This ensures messages only reach the testing address during development.

Sources: src/Mailer.php351-359

Message Lifecycle Steps


Message Lifecycle State Diagram

Sources: src/Mailer.php215-264 src/Mailer.php425-448 src/Mailer.php351-359

Transport Integration

The Mailer class delegates actual message transmission to Symfony's transport layer.

Sending via Transport

The sendSymfonyMessage() method performs the actual send operation:


This method:

  1. Creates a Symfony Envelope from the Email message (extracts sender/recipients from message headers)
  2. Calls the transport's send() method
  3. Returns the SymfonySentMessage (contains message ID, original message, etc.)

The empty finally block suggests this may be a placeholder for resource cleanup or logging in future implementations.

Sources: src/Mailer.php453-459

Transport Access Methods

The Mailer provides getter and setter methods for transport management:


These methods enable:

  • Transport inspection: Access underlying transport for configuration
  • Runtime swapping: Change transport without creating new mailer (useful for testing)
  • Pooling integration: Allow object pool to manage transport lifecycle

Sources: src/Mailer.php488-507

View Factory Access


This accessor allows external code to inspect or extend the view rendering capabilities.

Sources: src/Mailer.php495-499

Transport Layer Integration


Transport Layer Abstraction

The Mailer class is transport-agnostic. The MailManager (see Mail Manager and Factory Pattern) creates transports based on configuration, and the Mailer simply invokes the TransportInterface::send() method. This design allows swapping transports at runtime or using composite transports like failover/round-robin.

Sources: src/Mailer.php453-507

Summary

The Mailer class provides:

CapabilityMethodsPurpose
Global AddressingalwaysFrom(), alwaysTo(), alwaysReplyTo(), alwaysReturnPath()Configure default addresses for all messages
Fluent Interfaceto(), cc(), bcc()Create PendingMail instances for recipient configuration
Synchronous Sendingsend(), html(), raw(), plain(), sendNow()Immediate message dispatch
Asynchronous Sendingqueue(), later(), queueOn(), laterOn()Deferred message dispatch via queue
View Renderingrender(), renderView(), parseView(), addContent()Transform templates into email content
Event IntegrationshouldSendMessage(), dispatchSentEvent()Lifecycle hooks for logging, testing, modification
Transport ManagementsendSymfonyMessage(), getSymfonyTransport(), setSymfonyTransport()Interface with transport layer

The Mailer serves as the central orchestrator, coordinating view rendering, event dispatching, transport communication, and queue integration to provide a complete email sending solution.

Sources: src/Mailer.php1-518

Refresh this wiki

On this page