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
$_modelFactories
A list of overridden model factory functions.
protected
array<string|int, callable|LocatorInterface>
$_modelFactories
= []
$_modelType
The model type to use.
protected
string
$_modelType
= 'Table'
$_tableLocator
Table locator instance
protected
LocatorInterface|null
$_tableLocator
$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
$message
Message instance.
protected
Message
$message
$messageClass
Message class name.
protected
string
$messageClass
= \Cake\Mailer\Message::class
Tags
$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.
$renderer
Email Renderer
protected
Renderer|null
$renderer
$transport
The transport instance to use for sending mail.
protected
AbstractTransport|null
$transport
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
$thisaddBcc()
public
addBcc([mixed $email = ][, mixed $name = null ]) : $this
Add "bcc" address. Message::addBcc()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thisaddCc()
public
addCc([mixed $email = ][, mixed $name = null ]) : $this
Add "cc" address. Message::addCc()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thisaddHeaders()
public
addHeaders([array<string|int, mixed> $headers = ]) : $this
Add header for the message. Message::addHeaders()
Parameters
- $headers : array<string|int, mixed> =
Return values
$thisaddReplyTo()
public
addReplyTo([mixed $email = ][, mixed $name = null ]) : $this
Add "Reply-To" address. Message::addReplyTo()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thisaddTo()
public
addTo([mixed $email = ][, mixed $name = null ]) : $this
Add "To" address. Message::addTo()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thisconfigured()
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
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
Return values
TablegetAttachments()
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>|stringgetCc()
public
getCc() : array<string|int, mixed>
Gets "cc" address. Message::getCc()
Return values
array<string|int, mixed>getCharset()
public
getCharset() : string
Charset getter. Message::getCharset()
Return values
stringgetConfig()
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
Return values
mixed —Configuration data at the named key.
getDomain()
public
getDomain() : string
Gets domain. Message::getDomain()
Return values
stringgetDsnClassMap()
Returns the DSN class map for this class.
public
static getDsnClassMap() : array<string, string>
Tags
Return values
array<string, string>getEmailFormat()
public
getEmailFormat() : string
Gets email format. Message::getEmailFormat()
Return values
stringgetFrom()
public
getFrom() : array<string|int, mixed>
Gets "from" address. Message::getFrom()
Return values
array<string|int, mixed>getHeaderCharset()
public
getHeaderCharset() : string
HeaderCharset getter. Message::getHeaderCharset()
Return values
stringgetHeaders()
public
getHeaders([array<string|int, mixed> $include = [] ]) : $this
Get list of headers. Message::getHeaders()
Parameters
- $include : array<string|int, mixed> = []
Return values
$thisgetMessage()
Get message instance.
public
getMessage() : Message
Return values
MessagegetMessageId()
public
getMessageId() : string|bool
Gets message ID. Message::getMessageId()
Return values
string|boolgetModelType()
Get the model type to be used by this class
public
getModelType() : string
Return values
stringgetReadReceipt()
public
getReadReceipt() : array<string|int, mixed>
Gets Read Receipt (Disposition-Notification-To header). Message::getReadReceipt()
Return values
array<string|int, mixed>getRenderer()
Get email renderer.
public
getRenderer() : Renderer
Return values
RenderergetReplyTo()
public
getReplyTo() : array<string|int, mixed>
Gets "Reply-To" address. Message::getReplyTo()
Return values
array<string|int, mixed>getReturnPath()
public
getReturnPath() : array<string|int, mixed>
Gets return path. Message::getReturnPath()
Return values
array<string|int, mixed>getSender()
public
getSender() : array<string|int, mixed>
Gets "sender" address. Message::getSender()
Return values
array<string|int, mixed>getSubject()
public
getSubject() : string
Gets subject. Message::getSubject()
Return values
stringgetTableLocator()
Gets the table locator.
public
getTableLocator() : LocatorInterface
Return values
LocatorInterfacegetTo()
public
getTo() : array<string|int, mixed>
Gets "to" address. Message::getTo()
Return values
array<string|int, mixed>getTransport()
Gets the transport.
public
getTransport() : AbstractTransport
Return values
AbstractTransportimplementedEvents()
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 likeApp\Model\Table\PostsTable::class
. - $modelType : string|null = null
-
The type of repository to load. Defaults to the getModelType() value.
Tags
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
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
$thisreset()
Reset all the internal variables to be able to send out a new email.
public
reset() : $this
Return values
$thissend()
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
Return values
array<string|int, mixed>set()
Sets email view vars.
public
set(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
$thissetAttachments()
public
setAttachments([mixed $attachments = ]) : $this
Add attachments to the email message. Message::setAttachments()
Parameters
- $attachments : mixed =
Return values
$thissetBcc()
public
setBcc([mixed $email = ][, mixed $name = null ]) : $this
Sets "bcc" address. Message::setBcc()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thissetCc()
public
setCc([mixed $email = ][, mixed $name = null ]) : $this
Sets "cc" address. Message::setCc()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thissetCharset()
public
setCharset([mixed $charset = ]) : $this
Charset setter. Message::setCharset()
Parameters
- $charset : mixed =
Return values
$thissetConfig()
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
setDomain()
public
setDomain([mixed $domain = ]) : $this
Sets domain. Message::setDomain()
Parameters
- $domain : mixed =
Return values
$thissetDsnClassMap()
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
setEmailFormat()
public
setEmailFormat([mixed $format = ]) : $this
Sets email format. Message::getHeaders()
Parameters
- $format : mixed =
Return values
$thissetFrom()
public
setFrom([mixed $email = ][, mixed $name = null ]) : $this
Sets "from" address. Message::setFrom()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thissetHeaderCharset()
public
setHeaderCharset([mixed $charset = ]) : $this
HeaderCharset setter. Message::setHeaderCharset()
Parameters
- $charset : mixed =
Return values
$thissetHeaders()
public
setHeaders([array<string|int, mixed> $headers = ]) : $this
Sets headers for the message. Message::setHeaders()
Parameters
- $headers : array<string|int, mixed> =
Return values
$thissetMessage()
Set message instance.
public
setMessage(Message $message) : $this
Parameters
- $message : Message
-
Message instance.
Return values
$thissetMessageId()
public
setMessageId([mixed $message = ]) : $this
Sets message ID. Message::setMessageId()
Parameters
- $message : mixed =
Return values
$thissetModelType()
Set the model type to be used by this class
public
setModelType(string $modelType) : $this
Parameters
- $modelType : string
-
The model type
Return values
$thissetProfile()
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
$thissetReadReceipt()
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
$thissetRenderer()
Set email renderer.
public
setRenderer(Renderer $renderer) : $this
Parameters
- $renderer : Renderer
-
Render instance.
Return values
$thissetReplyTo()
public
setReplyTo([mixed $email = ][, mixed $name = null ]) : $this
Sets "Reply-To" address. Message::setReplyTo()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thissetReturnPath()
public
setReturnPath([mixed $email = ][, mixed $name = null ]) : $this
Sets return path. Message::setReturnPath()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thissetSender()
public
setSender([mixed $email = ][, mixed $name = null ]) : $this
Sets "sender" address. Message::setSender()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thissetSubject()
public
setSubject([mixed $subject = ]) : $this
Sets subject. Message::setSubject()
Parameters
- $subject : mixed =
Return values
$thissetTableLocator()
Sets the table locator.
public
setTableLocator(LocatorInterface $tableLocator) : $this
Parameters
- $tableLocator : LocatorInterface
-
LocatorInterface instance.
Return values
$thissetTo()
public
setTo([mixed $email = ][, mixed $name = null ]) : $this
Sets "to" address. Message::setTo()
Parameters
- $email : mixed =
- $name : mixed = null
Return values
$thissetTransport()
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
Return values
$thissetViewVars()
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
$thisviewBuilder()
Get the view builder.
public
viewBuilder() : ViewBuilder
Return values
ViewBuilder_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
stringlogDelivery()
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
restore()
Restore message, renderer, transport instances to state before an action was run.
protected
restore() : $this
Return values
$thissetLogConfig()
Set logging config.
protected
setLogConfig(array<string, mixed>|string|true $log) : void
Parameters
- $log : array<string, mixed>|string|true
-
Log config.