Fr3nch13/CakePHP Utilities

Mailer
in package
implements EventListenerInterface uses ModelAwareTrait, LocatorAwareTrait, StaticConfigTrait

Mailer base class.

Mailer classes let you encapsulate related Email logic into a reusable and testable class.

Defining Messages

Mailers make it easy for you to define methods that handle email formatting logic. For example:

class UserMailer extends Mailer
{
    public function resetPassword($user)
    {
        $this
            ->setSubject('Reset Password')
            ->setTo($user->email)
            ->set(['token' => $user->token]);
    }
}

Is a trivial example but shows how a mailer could be declared.

Sending Messages

After you have defined some messages you will want to send them:

$mailer = new UserMailer();
$mailer->send('resetPassword', $user);

Event Listener

Mailers can also subscribe to application event allowing you to decouple email delivery from your application code. By re-declaring the implementedEvents() method you can define event handlers that can convert events into email. For example, if your application had a user registration event:

public function implementedEvents(): array
{
    return [
        'Model.afterSave' => 'onRegistration',
    ];
}

public function onRegistration(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
    if ($entity->isNew()) {
         $this->send('welcome', [$entity]);
    }
}

The onRegistration method converts the application event into a mailer method. Our mailer could either be registered in the application bootstrap, or in the Table class' initialize() hook.

Attributes
#[AllowDynamicProperties]

Table of Contents

Interfaces

EventListenerInterface
Objects implementing this interface should declare the `implementedEvents()` method to notify the event manager what methods should be called when an event is triggered.

Properties

$name  : string
Mailer's name.
$_config  : array<string, mixed>
Configuration sets.
$_dsnClassMap  : array<string, string>
Mailer driver class map.
$_modelFactories  : array<string|int, callable|LocatorInterface>
A list of overridden model factory functions.
$_modelType  : string
The model type to use.
$_tableLocator  : LocatorInterface|null
Table locator instance
$clonedInstances  : array<string, mixed>
Hold message, renderer and transport instance for restoring after running a mailer action.
$defaultTable  : string|null
This object's default table alias.
$logConfig  : array<string|int, mixed>|null
$message  : Message
Message instance.
$messageClass  : string
Message class name.
$modelClass  : string|null
This object's primary model class name. Should be a plural form.
$renderer  : Renderer|null
Email Renderer
$transport  : AbstractTransport|null
The transport instance to use for sending mail.

Methods

__call()  : $this|mixed
Magic method to forward method class to Message instance.
__construct()  : mixed
Constructor
addAttachments()  : $this
addBcc()  : $this
addCc()  : $this
addHeaders()  : $this
addReplyTo()  : $this
addTo()  : $this
configured()  : array<string|int, string>
Returns an array containing the named configurations
deliver()  : array<string|int, mixed>
Render content and send email using configured transport.
drop()  : bool
Drops a constructed adapter.
fetchTable()  : Table
Convenience method to get a table instance.
getAttachments()  : array<string|int, mixed>
getBcc()  : array<string|int, mixed>
getBody()  : array<string|int, mixed>|string
getCc()  : array<string|int, mixed>
getCharset()  : string
getConfig()  : mixed|null
Reads existing configuration.
getConfigOrFail()  : mixed
Reads existing configuration for a specific key.
getDomain()  : string
getDsnClassMap()  : array<string, string>
Returns the DSN class map for this class.
getEmailFormat()  : string
getFrom()  : array<string|int, mixed>
getHeaderCharset()  : string
getHeaders()  : $this
getMessage()  : Message
Get message instance.
getMessageId()  : string|bool
getModelType()  : string
Get the model type to be used by this class
getReadReceipt()  : array<string|int, mixed>
getRenderer()  : Renderer
Get email renderer.
getReplyTo()  : array<string|int, mixed>
getReturnPath()  : array<string|int, mixed>
getSender()  : array<string|int, mixed>
getSubject()  : string
getTableLocator()  : LocatorInterface
Gets the table locator.
getTo()  : array<string|int, mixed>
getTransport()  : AbstractTransport
Gets the transport.
implementedEvents()  : array<string, mixed>
Implemented events.
loadModel()  : RepositoryInterface
Loads and constructs repository objects required by this object
modelFactory()  : void
Override a existing callable to generate repositories of a given type.
parseDsn()  : array<string, mixed>
Parses a DSN into a valid connection configuration
render()  : $this
Render content and set message body.
reset()  : $this
Reset all the internal variables to be able to send out a new email.
send()  : array<string|int, mixed>
Sends email.
set()  : $this
Sets email view vars.
setAttachments()  : $this
setBcc()  : $this
setCc()  : $this
setCharset()  : $this
setConfig()  : void
This method can be used to define configuration adapters for an application.
setDomain()  : $this
setDsnClassMap()  : void
Updates the DSN class map for this class.
setEmailFormat()  : $this
setFrom()  : $this
setHeaderCharset()  : $this
setHeaders()  : $this
setMessage()  : $this
Set message instance.
setMessageId()  : $this
setModelType()  : $this
Set the model type to be used by this class
setProfile()  : $this
Sets the configuration profile to use for this instance.
setReadReceipt()  : $this
setRenderer()  : $this
Set email renderer.
setReplyTo()  : $this
setReturnPath()  : $this
setSender()  : $this
setSubject()  : $this
setTableLocator()  : $this
Sets the table locator.
setTo()  : $this
setTransport()  : $this
Sets the transport.
setViewVars()  : $this
Sets email view vars.
viewBuilder()  : ViewBuilder
Get the view builder.
_setModelClass()  : void
Set the modelClass property based on conventions.
flatten()  : string
Converts given value to string
logDelivery()  : void
Log the email message delivery.
restore()  : $this
Restore message, renderer, transport instances to state before an action was run.
setLogConfig()  : void
Set logging config.

Properties

$name

Mailer's name.

public static string $name

$_config

Configuration sets.

protected static array<string, mixed> $_config = []

$_dsnClassMap

Mailer driver class map.

protected static array<string, string> $_dsnClassMap = []
Tags
psalm-var

array<string, class-string>

$_modelType

The model type to use.

protected string $_modelType = 'Table'

$clonedInstances

Hold message, renderer and transport instance for restoring after running a mailer action.

protected array<string, mixed> $clonedInstances = ['message' => null, 'renderer' => null, 'transport' => null]

$defaultTable

This object's default table alias.

protected string|null $defaultTable = null

$logConfig

protected array<string|int, mixed>|null $logConfig = null

$messageClass

Message class name.

protected string $messageClass = \Cake\Mailer\Message::class
Tags
psalm-var

class-string<\Cake\Mailer\Message>

$modelClass

This object's primary model class name. Should be a plural form.

Use Cake\ORM\Locator\LocatorAwareTrait::$defaultTable instead.

protected string|null $modelClass

CakePHP will not inflect the name.

Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use Plugin.Comments style names to correctly load models from the correct plugin.

Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.

Methods

__call()

Magic method to forward method class to Message instance.

public __call(string $method, array<string|int, mixed> $args) : $this|mixed
Parameters
$method : string

Method name.

$args : array<string|int, mixed>

Method arguments

Return values
$this|mixed

__construct()

Constructor

public __construct([array<string, mixed>|string|null $config = null ]) : mixed
Parameters
$config : array<string, mixed>|string|null = null

Array of configs, or string to load configs from app.php

addAttachments()

public addAttachments([mixed $attachments = ]) : $this

Add attachments. Message::addAttachments()

Parameters
$attachments : mixed =
Return values
$this

addBcc()

public addBcc([mixed $email = ][, mixed $name = null ]) : $this

Add "bcc" address. Message::addBcc()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

addCc()

public addCc([mixed $email = ][, mixed $name = null ]) : $this

Add "cc" address. Message::addCc()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

addHeaders()

public addHeaders([array<string|int, mixed> $headers = ]) : $this

Add header for the message. Message::addHeaders()

Parameters
$headers : array<string|int, mixed> =
Return values
$this

addReplyTo()

public addReplyTo([mixed $email = ][, mixed $name = null ]) : $this

Add "Reply-To" address. Message::addReplyTo()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

addTo()

public addTo([mixed $email = ][, mixed $name = null ]) : $this

Add "To" address. Message::addTo()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

configured()

Returns an array containing the named configurations

public static configured() : array<string|int, string>
Return values
array<string|int, string>

Array of configurations.

deliver()

Render content and send email using configured transport.

public deliver([string $content = '' ]) : array<string|int, mixed>
Parameters
$content : string = ''

Content.

Tags
psalm-return

array{headers: string, message: string}

Return values
array<string|int, mixed>

drop()

Drops a constructed adapter.

public static drop(string $config) : bool

If you wish to modify an existing configuration, you should drop it, change configuration and then re-add it.

If the implementing objects supports a $_registry object the named configuration will also be unloaded from the registry.

Parameters
$config : string

An existing configuration you wish to remove.

Return values
bool

Success of the removal, returns false when the config does not exist.

fetchTable()

Convenience method to get a table instance.

public fetchTable([string|null $alias = null ][, array<string, mixed> $options = [] ]) : Table
Parameters
$alias : string|null = null

The alias name you want to get. Should be in CamelCase format. If null then the value of $defaultTable property is used.

$options : array<string, mixed> = []

The options you want to build the table with. If a table has already been loaded the registry options will be ignored.

Tags
throws
CakeException

If $alias argument and $defaultTable property both are null.

see
TableLocator::get()
since
4.3.0
Return values
Table

getAttachments()

public getAttachments() : array<string|int, mixed>

Gets attachments to the email message. Message::getAttachments()

Return values
array<string|int, mixed>

getBcc()

public getBcc() : array<string|int, mixed>

Gets "bcc" address. Message::getBcc()

Return values
array<string|int, mixed>

getBody()

public getBody([string|null $type = null ]) : array<string|int, mixed>|string

Get generated message body as array. Message::getBody()

Parameters
$type : string|null = null
Return values
array<string|int, mixed>|string

getCc()

public getCc() : array<string|int, mixed>

Gets "cc" address. Message::getCc()

Return values
array<string|int, mixed>

getConfig()

Reads existing configuration.

public static getConfig(string $key) : mixed|null
Parameters
$key : string

The name of the configuration.

Return values
mixed|null

Configuration data at the named key or null if the key does not exist.

getConfigOrFail()

Reads existing configuration for a specific key.

public static getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The name of the configuration.

Tags
throws
InvalidArgumentException

If value does not exist.

Return values
mixed

Configuration data at the named key.

getDsnClassMap()

Returns the DSN class map for this class.

public static getDsnClassMap() : array<string, string>
Tags
psalm-return

array<string, class-string>

Return values
array<string, string>

getFrom()

public getFrom() : array<string|int, mixed>

Gets "from" address. Message::getFrom()

Return values
array<string|int, mixed>

getHeaders()

public getHeaders([array<string|int, mixed> $include = [] ]) : $this

Get list of headers. Message::getHeaders()

Parameters
$include : array<string|int, mixed> = []
Return values
$this

getModelType()

Get the model type to be used by this class

public getModelType() : string
Return values
string

getReadReceipt()

public getReadReceipt() : array<string|int, mixed>

Gets Read Receipt (Disposition-Notification-To header). Message::getReadReceipt()

Return values
array<string|int, mixed>

getReplyTo()

public getReplyTo() : array<string|int, mixed>

Gets "Reply-To" address. Message::getReplyTo()

Return values
array<string|int, mixed>

getSender()

public getSender() : array<string|int, mixed>

Gets "sender" address. Message::getSender()

Return values
array<string|int, mixed>

getTo()

public getTo() : array<string|int, mixed>

Gets "to" address. Message::getTo()

Return values
array<string|int, mixed>

implementedEvents()

Implemented events.

public implementedEvents() : array<string, mixed>
Return values
array<string, mixed>

loadModel()

Loads and constructs repository objects required by this object

public loadModel([string|null $modelClass = null ][, string|null $modelType = null ]) : RepositoryInterface

Use LocatorAwareTrait::fetchTable() instead.

Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.

If a repository provider does not return an object a MissingModelException will be thrown.

Parameters
$modelClass : string|null = null

Name of model class to load. Defaults to $this->modelClass. The name can be an alias like 'Post' or FQCN like App\Model\Table\PostsTable::class.

$modelType : string|null = null

The type of repository to load. Defaults to the getModelType() value.

Tags
throws
MissingModelException

If the model class cannot be found.

throws
UnexpectedValueException

If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty.

Return values
RepositoryInterface

The model instance created.

modelFactory()

Override a existing callable to generate repositories of a given type.

public modelFactory(string $type, LocatorInterface|callable $factory) : void
Parameters
$type : string

The name of the repository type the factory function is for.

$factory : LocatorInterface|callable

The factory function used to create instances.

parseDsn()

Parses a DSN into a valid connection configuration

public static parseDsn(string $dsn) : array<string, mixed>

This method allows setting a DSN using formatting similar to that used by PEAR::DB. The following is an example of its usage:

$dsn = 'mysql://user:pass@localhost/database?';
$config = ConnectionManager::parseDsn($dsn);

$dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
$config = Log::parseDsn($dsn);

$dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
$config = Email::parseDsn($dsn);

$dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
$config = Cache::parseDsn($dsn);

$dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
$config = Cache::parseDsn($dsn);

For all classes, the value of scheme is set as the value of both the className unless they have been otherwise specified.

Note that querystring arguments are also parsed and set as values in the returned configuration.

Parameters
$dsn : string

The DSN string to convert to a configuration array

Tags
throws
InvalidArgumentException

If not passed a string, or passed an invalid string

Return values
array<string, mixed>

The configuration array to be stored after parsing the DSN

render()

Render content and set message body.

public render([string $content = '' ]) : $this
Parameters
$content : string = ''

Content.

Return values
$this

reset()

Reset all the internal variables to be able to send out a new email.

public reset() : $this
Return values
$this

send()

Sends email.

public send([string|null $action = null ][, array<string|int, mixed> $args = [] ][, array<string|int, mixed> $headers = [] ]) : array<string|int, mixed>
Parameters
$action : string|null = null

The name of the mailer action to trigger. If no action is specified then all other method arguments will be ignored.

$args : array<string|int, mixed> = []

Arguments to pass to the triggered mailer action.

$headers : array<string|int, mixed> = []

Headers to set.

Tags
throws
MissingActionException
throws
BadMethodCallException
psalm-return

array{headers: string, message: string}

Return values
array<string|int, mixed>

set()

Sets email view vars.

public set(array<string|int, mixed>|string $key[, mixed $value = null ]) : $this

Use instead.

Parameters
$key : array<string|int, mixed>|string

Variable name or hash of view variables.

$value : mixed = null

View variable value.

Return values
$this

setAttachments()

public setAttachments([mixed $attachments = ]) : $this

Add attachments to the email message. Message::setAttachments()

Parameters
$attachments : mixed =
Return values
$this

setBcc()

public setBcc([mixed $email = ][, mixed $name = null ]) : $this

Sets "bcc" address. Message::setBcc()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setCc()

public setCc([mixed $email = ][, mixed $name = null ]) : $this

Sets "cc" address. Message::setCc()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setCharset()

public setCharset([mixed $charset = ]) : $this

Charset setter. Message::setCharset()

Parameters
$charset : mixed =
Return values
$this

setConfig()

This method can be used to define configuration adapters for an application.

public static setConfig(array<string, mixed>|string $key[, mixed $config = null ]) : void

To change an adapter's configuration at runtime, first drop the adapter and then reconfigure it.

Adapters will not be constructed until the first operation is done.

Usage

Assuming that the class' name is Cache the following scenarios are supported:

Setting a cache engine up.

Cache::setConfig('default', $settings);

Injecting a constructed adapter in:

Cache::setConfig('default', $instance);

Configure multiple adapters at once:

Cache::setConfig($arrayOfConfig);
Parameters
$key : array<string, mixed>|string

The name of the configuration, or an array of multiple configs.

$config : mixed = null

Configuration value. Generally an array of name => configuration data for adapter.

Tags
throws
BadMethodCallException

When trying to modify an existing config.

throws
LogicException

When trying to store an invalid structured config array.

setDomain()

public setDomain([mixed $domain = ]) : $this

Sets domain. Message::setDomain()

Parameters
$domain : mixed =
Return values
$this

setDsnClassMap()

Updates the DSN class map for this class.

public static setDsnClassMap(array<string, string> $map) : void
Parameters
$map : array<string, string>

Additions/edits to the class map to apply.

Tags
psalm-param

array<string, class-string> $map

setEmailFormat()

public setEmailFormat([mixed $format = ]) : $this

Sets email format. Message::getHeaders()

Parameters
$format : mixed =
Return values
$this

setFrom()

public setFrom([mixed $email = ][, mixed $name = null ]) : $this

Sets "from" address. Message::setFrom()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setHeaderCharset()

public setHeaderCharset([mixed $charset = ]) : $this

HeaderCharset setter. Message::setHeaderCharset()

Parameters
$charset : mixed =
Return values
$this

setHeaders()

public setHeaders([array<string|int, mixed> $headers = ]) : $this

Sets headers for the message. Message::setHeaders()

Parameters
$headers : array<string|int, mixed> =
Return values
$this

setMessage()

Set message instance.

public setMessage(Message $message) : $this
Parameters
$message : Message

Message instance.

Return values
$this

setMessageId()

public setMessageId([mixed $message = ]) : $this

Sets message ID. Message::setMessageId()

Parameters
$message : mixed =
Return values
$this

setModelType()

Set the model type to be used by this class

public setModelType(string $modelType) : $this
Parameters
$modelType : string

The model type

Return values
$this

setProfile()

Sets the configuration profile to use for this instance.

public setProfile(array<string, mixed>|string $config) : $this
Parameters
$config : array<string, mixed>|string

String with configuration name, or an array with config.

Return values
$this

setReadReceipt()

public setReadReceipt([mixed $email = ][, mixed $name = null ]) : $this

Sets Read Receipt (Disposition-Notification-To header). Message::setReadReceipt()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setRenderer()

Set email renderer.

public setRenderer(Renderer $renderer) : $this
Parameters
$renderer : Renderer

Render instance.

Return values
$this

setReplyTo()

public setReplyTo([mixed $email = ][, mixed $name = null ]) : $this

Sets "Reply-To" address. Message::setReplyTo()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setReturnPath()

public setReturnPath([mixed $email = ][, mixed $name = null ]) : $this

Sets return path. Message::setReturnPath()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setSender()

public setSender([mixed $email = ][, mixed $name = null ]) : $this

Sets "sender" address. Message::setSender()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setSubject()

public setSubject([mixed $subject = ]) : $this

Sets subject. Message::setSubject()

Parameters
$subject : mixed =
Return values
$this

setTo()

public setTo([mixed $email = ][, mixed $name = null ]) : $this

Sets "to" address. Message::setTo()

Parameters
$email : mixed =
$name : mixed = null
Return values
$this

setTransport()

Sets the transport.

public setTransport(AbstractTransport|string $name) : $this

When setting the transport you can either use the name of a configured transport or supply a constructed transport.

Parameters
$name : AbstractTransport|string

Either the name of a configured transport, or a transport instance.

Tags
throws
LogicException

When the chosen transport lacks a send method.

throws
InvalidArgumentException

When $name is neither a string nor an object.

Return values
$this

setViewVars()

Sets email view vars.

public setViewVars(array<string|int, mixed>|string $key[, mixed $value = null ]) : $this
Parameters
$key : array<string|int, mixed>|string

Variable name or hash of view variables.

$value : mixed = null

View variable value.

Return values
$this

_setModelClass()

Set the modelClass property based on conventions.

protected _setModelClass(string $name) : void

If the property is already set it will not be overwritten

Parameters
$name : string

Class name.

flatten()

Converts given value to string

protected flatten(array<string|int, string>|string $value) : string
Parameters
$value : array<string|int, string>|string

The value to convert

Return values
string

logDelivery()

Log the email message delivery.

protected logDelivery(array<string|int, mixed> $contents) : void
Parameters
$contents : array<string|int, mixed>

The content with 'headers' and 'message' keys.

Tags
psalm-param

array{headers: string, message: string} $contents

restore()

Restore message, renderer, transport instances to state before an action was run.

protected restore() : $this
Return values
$this

setLogConfig()

Set logging config.

protected setLogConfig(array<string, mixed>|string|true $log) : void
Parameters
$log : array<string, mixed>|string|true

Log config.


        
On this page

Search results