Class Mailer
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.
Property Summary
-
$_config protected static
array
Configuration sets.
-
$_dsnClassMap protected static
array
Mailer driver class map.
-
$_modelFactories protected
array
A list of overridden model factory functions.
-
$_modelType protected
string
The model type to use.
-
$clonedInstances protected
array
Hold message, renderer and transport instance for restoring after runnning a mailer action.
-
$logConfig protected
array|null
-
$message protected
Cake\Mailer\Message
Message instance.
-
$messageClass protected
string
Message class name.
-
$modelClass protected
string|null
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
-
$name public static
string
Mailer's name.
-
$renderer protected
Cake\Mailer\Renderer|null
Email Renderer
-
$transport protected
Cake\Mailer\AbstractTransport|null
The transport instance to use for sending mail.
Method Summary
-
__call() public
Magic method to forward method class to Message instance.
-
__construct() public
Constructor
-
_setModelClass() protected
Set the modelClass property based on conventions.
-
addAttachments() public @method
Add attachments. {@see \Cake\Mailer\Message::addAttachments()}
-
addBcc() public @method
Add "bcc" address. {@see \Cake\Mailer\Message::addBcc()}
-
addCc() public @method
Add "cc" address. {@see \Cake\Mailer\Message::addCc()}
-
addHeaders() public @method
Add header for the message. {@see \Cake\Mailer\Message::addHeaders()}
-
addTo() public @method
Add "To" address. {@see \Cake\Mailer\Message::addTo()}
-
configured() public static
Returns an array containing the named configurations
-
deliver() public
Render content and send email using configured transport.
-
drop() public static
Drops a constructed adapter.
-
flatten() protected
Converts given value to string
-
getAttachments() public @method
Gets attachments to the email message. {@see \Cake\Mailer\Message::getAttachments()}
-
getBcc() public @method
Gets "bcc" address. {@see \Cake\Mailer\Message::getBcc()}
-
getBody() public @method
Get generated message body as array. {@see \Cake\Mailer\Message::getBody()}
-
getCc() public @method
Gets "cc" address. {@see \Cake\Mailer\Message::getCc()}
-
getCharset() public @method
Charset getter. {@see \Cake\Mailer\Message::getCharset()}
-
getConfig() public static
Reads existing configuration.
-
getConfigOrFail() public static
Reads existing configuration for a specific key.
-
getDomain() public @method
Gets domain. {@see \Cake\Mailer\Message::getDomain()}
-
getDsnClassMap() public static
Returns the DSN class map for this class.
-
getEmailFormat() public @method
Gets email format. {@see \Cake\Mailer\Message::getEmailFormat()}
-
getFrom() public @method
Gets "from" address. {@see \Cake\Mailer\Message::getFrom()}
-
getHeaderCharset() public @method
HeaderCharset getter. {@see \Cake\Mailer\Message::getHeaderCharset()}
-
getHeaders() public @method
Get list of headers. {@see \Cake\Mailer\Message::getHeaders()}
-
getMessage() public
Get message instance.
-
getMessageId() public @method
Gets message ID. {@see \Cake\Mailer\Message::getMessageId()}
-
getModelType() public
Get the model type to be used by this class
-
getReadReceipt() public @method
Gets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::getReadReceipt()}
-
getRenderer() public
Get email renderer.
-
getReplyTo() public @method
Gets "Reply-To" address. {@see \Cake\Mailer\Message::getReplyTo()}
-
getReturnPath() public @method
Gets return path. {@see \Cake\Mailer\Message::getReturnPath()}
-
getSender() public @method
Gets "sender" address. {@see \Cake\Mailer\Message::getSender()}
-
getSubject() public @method
Gets subject. {@see \Cake\Mailer\Message::getSubject()}
-
getTo() public @method
Gets "to" address. {@see \Cake\Mailer\Message::getTo()}
-
getTransport() public
Gets the transport.
-
implementedEvents() public
Implemented events.
-
loadModel() public
Loads and constructs repository objects required by this object
-
logDelivery() protected
Log the email message delivery.
-
modelFactory() public
Override a existing callable to generate repositories of a given type.
-
parseDsn() public static
Parses a DSN into a valid connection configuration
-
render() public
Render content and set message body.
-
reset() public
Reset all the internal variables to be able to send out a new email.
-
restore() protected
Restore message, renderer, transport instances to state before an action was run.
-
send() public
Sends email.
-
set() public deprecated
Sets email view vars.
-
setAttachments() public @method
Add attachments to the email message. {@see \Cake\Mailer\Message::setAttachments()}
-
setBcc() public @method
Sets "bcc" address. {@see \Cake\Mailer\Message::setBcc()}
-
setCc() public @method
Sets "cc" address. {@see \Cake\Mailer\Message::setCc()}
-
setCharset() public @method
Charset setter. {@see \Cake\Mailer\Message::setCharset()}
-
setConfig() public static
This method can be used to define configuration adapters for an application.
-
setDomain() public @method
Sets domain. {@see \Cake\Mailer\Message::setDomain()}
-
setDsnClassMap() public static
Updates the DSN class map for this class.
-
setEmailFormat() public @method
Sets email format. {@see \Cake\Mailer\Message::getHeaders()}
-
setFrom() public @method
Sets "from" address. {@see \Cake\Mailer\Message::setFrom()}
-
setHeaderCharset() public @method
HeaderCharset setter. {@see \Cake\Mailer\Message::setHeaderCharset()}
-
setHeaders() public @method
Sets headers for the message. {@see \Cake\Mailer\Message::setHeaders()}
-
setLogConfig() protected
Set logging config.
-
setMessage() public
Set message instance.
-
setMessageId() public @method
Sets message ID. {@see \Cake\Mailer\Message::setMessageId()}
-
setModelType() public
Set the model type to be used by this class
-
setProfile() public
Sets the configuration profile to use for this instance.
-
setReadReceipt() public @method
Sets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::setReadReceipt()}
-
setRenderer() public
Set email renderer.
-
setReplyTo() public @method
Sets "Reply-To" address. {@see \Cake\Mailer\Message::setReplyTo()}
-
setReturnPath() public @method
Sets return path. {@see \Cake\Mailer\Message::setReturnPath()}
-
setSender() public @method
Sets "sender" address. {@see \Cake\Mailer\Message::setSender()}
-
setSubject() public @method
Sets subject. {@see \Cake\Mailer\Message::setSubject()}
-
setTo() public @method
Sets "to" address. {@see \Cake\Mailer\Message::setTo()}
-
setTransport() public
Sets the transport.
-
setViewVars() public
Sets email view vars.
-
viewBuilder() public
Get the view builder.
Method Detail
__call() ¶ public
__call(string $method, array $args): $this|mixed
Magic method to forward method class to Message instance.
Parameters
-
string
$method Method name.
-
array
$args Method arguments
Returns
$this|mixed
__construct() ¶ public
__construct(array|string|null $config = null)
Constructor
Parameters
-
array|string|null
$config optional Array of configs, or string to load configs from app.php
_setModelClass() ¶ protected
_setModelClass(string $name): void
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
Parameters
-
string
$name Class name.
Returns
void
addAttachments() ¶ public @method
addAttachments(mixed $attachments): $this
Add attachments. {@see \Cake\Mailer\Message::addAttachments()}
Parameters
-
$attachments
Returns
$this
addBcc() ¶ public @method
addBcc(mixed $email, mixed $name = null): $this
Add "bcc" address. {@see \Cake\Mailer\Message::addBcc()}
Parameters
-
$email
-
$name optional
Returns
$this
addCc() ¶ public @method
addCc(mixed $email, mixed $name = null): $this
Add "cc" address. {@see \Cake\Mailer\Message::addCc()}
Parameters
-
$email
-
$name optional
Returns
$this
addHeaders() ¶ public @method
addHeaders(array $headers): $this
Add header for the message. {@see \Cake\Mailer\Message::addHeaders()}
Parameters
-
array
$headers
Returns
$this
addTo() ¶ public @method
addTo(mixed $email, mixed $name = null): $this
Add "To" address. {@see \Cake\Mailer\Message::addTo()}
Parameters
-
$email
-
$name optional
Returns
$this
configured() ¶ public static
configured(): string[]
Returns an array containing the named configurations
Returns
string[]
deliver() ¶ public
deliver(string $content = ''): array
Render content and send email using configured transport.
Parameters
-
string
$content optional Content.
Returns
array
drop() ¶ public static
drop(string $config): bool
Drops a constructed adapter.
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
-
string
$config An existing configuration you wish to remove.
Returns
bool
flatten() ¶ protected
flatten(string|array $value): string
Converts given value to string
Parameters
-
string|array
$value The value to convert
Returns
string
getAttachments() ¶ public @method
getAttachments(): array
Gets attachments to the email message. {@see \Cake\Mailer\Message::getAttachments()}
Returns
array
getBcc() ¶ public @method
getBcc(): array
Gets "bcc" address. {@see \Cake\Mailer\Message::getBcc()}
Returns
array
getBody() ¶ public @method
getBody(?string $type = null): string|array
Get generated message body as array. {@see \Cake\Mailer\Message::getBody()}
Parameters
-
?string
$type optional
Returns
string|array
getCc() ¶ public @method
getCc(): array
Gets "cc" address. {@see \Cake\Mailer\Message::getCc()}
Returns
array
getCharset() ¶ public @method
getCharset(): string
Charset getter. {@see \Cake\Mailer\Message::getCharset()}
Returns
string
getConfig() ¶ public static
getConfig(string $key): mixed|null
Reads existing configuration.
Parameters
-
string
$key The name of the configuration.
Returns
mixed|null
getConfigOrFail() ¶ public static
getConfigOrFail(string $key): mixed
Reads existing configuration for a specific key.
The config value for this key must exist, it can never be null.
Parameters
-
string
$key The name of the configuration.
Returns
mixed
Throws
InvalidArgumentException
If value does not exist.
getDomain() ¶ public @method
getDomain(): string
Gets domain. {@see \Cake\Mailer\Message::getDomain()}
Returns
string
getDsnClassMap() ¶ public static
getDsnClassMap(): string[]
Returns the DSN class map for this class.
Returns
string[]
getEmailFormat() ¶ public @method
getEmailFormat(): string
Gets email format. {@see \Cake\Mailer\Message::getEmailFormat()}
Returns
string
getFrom() ¶ public @method
getFrom(): array
Gets "from" address. {@see \Cake\Mailer\Message::getFrom()}
Returns
array
getHeaderCharset() ¶ public @method
getHeaderCharset(): string
HeaderCharset getter. {@see \Cake\Mailer\Message::getHeaderCharset()}
Returns
string
getHeaders() ¶ public @method
getHeaders(array $include = []): $this
Get list of headers. {@see \Cake\Mailer\Message::getHeaders()}
Parameters
-
array
$include optional
Returns
$this
getMessage() ¶ public
getMessage(): Cake\Mailer\Message
Get message instance.
Returns
Cake\Mailer\Message
getMessageId() ¶ public @method
getMessageId(): bool|string
Gets message ID. {@see \Cake\Mailer\Message::getMessageId()}
Returns
bool|string
getModelType() ¶ public
getModelType(): string
Get the model type to be used by this class
Returns
string
getReadReceipt() ¶ public @method
getReadReceipt(): array
Gets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::getReadReceipt()}
Returns
array
getRenderer() ¶ public
getRenderer(): Cake\Mailer\Renderer
Get email renderer.
Returns
Cake\Mailer\Renderer
getReplyTo() ¶ public @method
getReplyTo(): array
Gets "Reply-To" address. {@see \Cake\Mailer\Message::getReplyTo()}
Returns
array
getReturnPath() ¶ public @method
getReturnPath(): array
Gets return path. {@see \Cake\Mailer\Message::getReturnPath()}
Returns
array
getSender() ¶ public @method
getSender(): array
Gets "sender" address. {@see \Cake\Mailer\Message::getSender()}
Returns
array
getSubject() ¶ public @method
getSubject(): string
Gets subject. {@see \Cake\Mailer\Message::getSubject()}
Returns
string
getTo() ¶ public @method
getTo(): array
Gets "to" address. {@see \Cake\Mailer\Message::getTo()}
Returns
array
getTransport() ¶ public
getTransport(): Cake\Mailer\AbstractTransport
Gets the transport.
Returns
Cake\Mailer\AbstractTransport
implementedEvents() ¶ public
implementedEvents(): array
Implemented events.
Example:
public function implementedEvents()
{
return [
'Order.complete' => 'sendEmail',
'Article.afterBuy' => 'decrementInventory',
'User.onRegister' => ['callable' => 'logRegistration', 'priority' => 20, 'passParams' => true]
];
}
Returns
array
loadModel() ¶ public
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
Loads and constructs repository objects required by this object
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
-
string|null
$modelClass optional 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
.-
string|null
$modelType optional The type of repository to load. Defaults to the getModelType() value.
Returns
Cake\Datasource\RepositoryInterface
Throws
Cake\Datasource\Exception\MissingModelException
If the model class cannot be found.
UnexpectedValueException
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty.
logDelivery() ¶ protected
logDelivery(array $contents): void
Log the email message delivery.
Parameters
-
array
$contents The content with 'headers' and 'message' keys.
Returns
void
modelFactory() ¶ public
modelFactory(string $type, callable $factory): void
Override a existing callable to generate repositories of a given type.
Parameters
-
string
$type The name of the repository type the factory function is for.
-
callable
$factory The factory function used to create instances.
Returns
void
parseDsn() ¶ public static
parseDsn(string $dsn): array
Parses a DSN into a valid connection configuration
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
-
string
$dsn The DSN string to convert to a configuration array
Returns
array
Throws
InvalidArgumentException
If not passed a string, or passed an invalid string
render() ¶ public
render(string $content = ''): $this
Render content and set message body.
Parameters
-
string
$content optional Content.
Returns
$this
reset() ¶ public
reset(): $this
Reset all the internal variables to be able to send out a new email.
Returns
$this
restore() ¶ protected
restore(): $this
Restore message, renderer, transport instances to state before an action was run.
Returns
$this
send() ¶ public
send(string|null $action = null, array $args = [], array $headers = []): array
Sends email.
Parameters
-
string|null
$action optional The name of the mailer action to trigger. If no action is specified then all other method arguments will be ignored.
-
array
$args optional Arguments to pass to the triggered mailer action.
-
array
$headers optional Headers to set.
Returns
array
Throws
Cake\Mailer\Exception\MissingActionException
BadMethodCallException
set() ¶ public
set(string|array $key, mixed $value = null): $this
Sets email view vars.
Parameters
-
string|array
$key Variable name or hash of view variables.
-
mixed
$value optional View variable value.
Returns
$this
setAttachments() ¶ public @method
setAttachments(mixed $attachments): $this
Add attachments to the email message. {@see \Cake\Mailer\Message::setAttachments()}
Parameters
-
$attachments
Returns
$this
setBcc() ¶ public @method
setBcc(mixed $email, mixed $name = null): $this
Sets "bcc" address. {@see \Cake\Mailer\Message::setBcc()}
Parameters
-
$email
-
$name optional
Returns
$this
setCc() ¶ public @method
setCc(mixed $email, mixed $name = null): $this
Sets "cc" address. {@see \Cake\Mailer\Message::setCc()}
Parameters
-
$email
-
$name optional
Returns
$this
setCharset() ¶ public @method
setCharset(mixed $charset): $this
Charset setter. {@see \Cake\Mailer\Message::setCharset()}
Parameters
-
$charset
Returns
$this
setConfig() ¶ public static
setConfig(string|array $key, array|object|null $config = null): void
This method can be used to define configuration adapters for an application.
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
-
string|array
$key The name of the configuration, or an array of multiple configs.
-
array|object|null
$config optional An array of name => configuration data for adapter.
Returns
void
Throws
BadMethodCallException
When trying to modify an existing config.
LogicException
When trying to store an invalid structured config array.
setDomain() ¶ public @method
setDomain(mixed $domain): $this
Sets domain. {@see \Cake\Mailer\Message::setDomain()}
Parameters
-
$domain
Returns
$this
setDsnClassMap() ¶ public static
setDsnClassMap(string[] $map): void
Updates the DSN class map for this class.
Parameters
-
string[]
$map Additions/edits to the class map to apply.
Returns
void
setEmailFormat() ¶ public @method
setEmailFormat(mixed $format): $this
Sets email format. {@see \Cake\Mailer\Message::getHeaders()}
Parameters
-
$format
Returns
$this
setFrom() ¶ public @method
setFrom(mixed $email, mixed $name = null): $this
Sets "from" address. {@see \Cake\Mailer\Message::setFrom()}
Parameters
-
$email
-
$name optional
Returns
$this
setHeaderCharset() ¶ public @method
setHeaderCharset(mixed $charset): $this
HeaderCharset setter. {@see \Cake\Mailer\Message::setHeaderCharset()}
Parameters
-
$charset
Returns
$this
setHeaders() ¶ public @method
setHeaders(array $headers): $this
Sets headers for the message. {@see \Cake\Mailer\Message::setHeaders()}
Parameters
-
array
$headers
Returns
$this
setLogConfig() ¶ protected
setLogConfig(string|array|true $log): void
Set logging config.
Parameters
-
string|array|true
$log Log config.
Returns
void
setMessage() ¶ public
setMessage(Cake\Mailer\Message $message): $this
Set message instance.
Parameters
-
Cake\Mailer\Message
$message Message instance.
Returns
$this
setMessageId() ¶ public @method
setMessageId(mixed $message): $this
Sets message ID. {@see \Cake\Mailer\Message::setMessageId()}
Parameters
-
$message
Returns
$this
setModelType() ¶ public
setModelType(string $modelType): $this
Set the model type to be used by this class
Parameters
-
string
$modelType The model type
Returns
$this
setProfile() ¶ public
setProfile(string|array $config): $this
Sets the configuration profile to use for this instance.
Parameters
-
string|array
$config String with configuration name, or an array with config.
Returns
$this
setReadReceipt() ¶ public @method
setReadReceipt(mixed $email, mixed $name = null): $this
Sets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::setReadReceipt()}
Parameters
-
$email
-
$name optional
Returns
$this
setRenderer() ¶ public
setRenderer(Cake\Mailer\Renderer $renderer): $this
Set email renderer.
Parameters
-
Cake\Mailer\Renderer
$renderer Render instance.
Returns
$this
setReplyTo() ¶ public @method
setReplyTo(mixed $email, mixed $name = null): $this
Sets "Reply-To" address. {@see \Cake\Mailer\Message::setReplyTo()}
Parameters
-
$email
-
$name optional
Returns
$this
setReturnPath() ¶ public @method
setReturnPath(mixed $email, mixed $name = null): $this
Sets return path. {@see \Cake\Mailer\Message::setReturnPath()}
Parameters
-
$email
-
$name optional
Returns
$this
setSender() ¶ public @method
setSender(mixed $email, mixed $name = null): $this
Sets "sender" address. {@see \Cake\Mailer\Message::setSender()}
Parameters
-
$email
-
$name optional
Returns
$this
setSubject() ¶ public @method
setSubject(mixed $subject): $this
Sets subject. {@see \Cake\Mailer\Message::setSubject()}
Parameters
-
$subject
Returns
$this
setTo() ¶ public @method
setTo(mixed $email, mixed $name = null): $this
Sets "to" address. {@see \Cake\Mailer\Message::setTo()}
Parameters
-
$email
-
$name optional
Returns
$this
setTransport() ¶ public
setTransport(string|Cake\Mailer\AbstractTransport $name): $this
Sets the transport.
When setting the transport you can either use the name of a configured transport or supply a constructed transport.
Parameters
-
string|Cake\Mailer\AbstractTransport
$name Either the name of a configured transport, or a transport instance.
Returns
$this
Throws
LogicException
When the chosen transport lacks a send method.
InvalidArgumentException
When $name is neither a string nor an object.
setViewVars() ¶ public
setViewVars(string|array $key, mixed $value = null): $this
Sets email view vars.
Parameters
-
string|array
$key Variable name or hash of view variables.
-
mixed
$value optional View variable value.
Returns
$this
viewBuilder() ¶ public
viewBuilder(): Cake\View\ViewBuilder
Get the view builder.
Returns
Cake\View\ViewBuilder
Property Detail
$clonedInstances ¶ protected
Hold message, renderer and transport instance for restoring after runnning a mailer action.
Type
array
$modelClass ¶ protected
This object's primary model class name. Should be a plural form. 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.
Type
string|null
$transport ¶ protected
The transport instance to use for sending mail.
Type
Cake\Mailer\AbstractTransport|null