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.
Properties summary
- $_config protected static
arrayConfiguration sets.
- $_dsnClassMap protected static
arrayMailer driver class map.
- $_modelFactories protected
(callable|\Cake\Datasource\Locator\LocatorInterface)[]A list of overridden model factory functions.
- $_modelType protected
stringThe model type to use.
- $clonedInstances protected
arrayHold message, renderer and transport instance for restoring after runnning a mailer action.
- $logConfig protected
array|null - $message protected
\Cake\Mailer\MessageMessage instance.
- $messageClass protected
stringMessage class name.
- $modelClass protected
string|nullThis object's primary model class name. Should be a plural form.
- $name public static
stringMailer's name.
- $renderer protected
\Cake\Mailer\Renderer|nullEmail Renderer
- $transport protected
\Cake\Mailer\AbstractTransport|nullThe transport instance to use for sending mail.
Method Summary
- getAttachments() public
Gets attachments to the email message. {@see \Cake\Mailer\Message::getAttachments()}
- getReadReceipt() public
Gets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::getReadReceipt()}
- restore() protected
Restore message, renderer, transport instances to state before an action was run.
- setAttachments() public
Add attachments to the email message. {@see \Cake\Mailer\Message::setAttachments()}
- setConfig() public static
This method can be used to define configuration adapters for an application.
- setReadReceipt() public
Sets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::setReadReceipt()}
Method Detail
__call() public
__call(string $method, array $args)
Magic method to forward method class to Message instance.
Parameters
-
string$method Method name.
-
array$args Method arguments
Returns
$this|mixed__construct() public
__construct(mixed $config)
Constructor
Parameters
-
array|string|null$config optional Array of configs, or string to load configs from app.php
_setModelClass() protected
_setModelClass(string $name)
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
Parameters
-
string$name Class name.
addAttachments() public
addAttachments(mixed $attachments)
Add attachments. {@see \Cake\Mailer\Message::addAttachments()}
Parameters
-
mixed$attachments
addBcc() public
addBcc(mixed $email, mixed $name)
Add "bcc" address. {@see \Cake\Mailer\Message::addBcc()}
Parameters
-
mixed$email -
mixed$name
addCc() public
addCc(mixed $email, mixed $name)
Add "cc" address. {@see \Cake\Mailer\Message::addCc()}
Parameters
-
mixed$email -
mixed$name
addHeaders() public
addHeaders(array $headers)
Add header for the message. {@see \Cake\Mailer\Message::addHeaders()}
Parameters
-
array$headers
addTo() public
addTo(mixed $email, mixed $name)
Add "To" address. {@see \Cake\Mailer\Message::addTo()}
Parameters
-
mixed$email -
mixed$name
configured() public static
configured()
Returns an array containing the named configurations
Returns
string[]Array of configurations.
deliver() public
deliver(string $content)
Render content and send email using configured transport.
Parameters
-
string$content optional Content.
Returns
arraydrop() public static
drop(string $config)
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
boolSuccess of the removal, returns false when the config does not exist.
flatten() protected
flatten(mixed $value)
Converts given value to string
Parameters
-
string|array$value The value to convert
Returns
stringgetAttachments() public
getAttachments()
Gets attachments to the email message. {@see \Cake\Mailer\Message::getAttachments()}
getBcc() public
getBcc()
Gets "bcc" address. {@see \Cake\Mailer\Message::getBcc()}
getBody() public
getBody(?string $type = null)
Get generated message body as array. {@see \Cake\Mailer\Message::getBody()}
Parameters
-
?string$type = null
getCc() public
getCc()
Gets "cc" address. {@see \Cake\Mailer\Message::getCc()}
getCharset() public
getCharset()
Charset getter. {@see \Cake\Mailer\Message::getCharset()}
getConfig() public static
getConfig(string $key)
Reads existing configuration.
Parameters
-
string$key The name of the configuration.
Returns
mixed|nullConfiguration data at the named key or null if the key does not exist.
getConfigOrFail() public static
getConfigOrFail(string $key)
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
mixedConfiguration data at the named key.
Throws
InvalidArgumentExceptionIf value does not exist.
getDomain() public
getDomain()
Gets domain. {@see \Cake\Mailer\Message::getDomain()}
getDsnClassMap() public static
getDsnClassMap()
Returns the DSN class map for this class.
Returns
string[]getEmailFormat() public
getEmailFormat()
Gets email format. {@see \Cake\Mailer\Message::getEmailFormat()}
getFrom() public
getFrom()
Gets "from" address. {@see \Cake\Mailer\Message::getFrom()}
getHeaderCharset() public
getHeaderCharset()
HeaderCharset getter. {@see \Cake\Mailer\Message::getHeaderCharset()}
getHeaders() public
getHeaders(array $include = [])
Get list of headers. {@see \Cake\Mailer\Message::getHeaders()}
Parameters
-
array$include = []
getMessage() public
getMessage()
Get message instance.
Returns
\Cake\Mailer\MessagegetMessageId() public
getMessageId()
Gets message ID. {@see \Cake\Mailer\Message::getMessageId()}
getModelType() public
getModelType()
Get the model type to be used by this class
Returns
stringgetReadReceipt() public
getReadReceipt()
Gets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::getReadReceipt()}
getRenderer() public
getRenderer()
Get email renderer.
Returns
\Cake\Mailer\RenderergetReplyTo() public
getReplyTo()
Gets "Reply-To" address. {@see \Cake\Mailer\Message::getReplyTo()}
getReturnPath() public
getReturnPath()
Gets return path. {@see \Cake\Mailer\Message::getReturnPath()}
getSender() public
getSender()
Gets "sender" address. {@see \Cake\Mailer\Message::getSender()}
getSubject() public
getSubject()
Gets subject. {@see \Cake\Mailer\Message::getSubject()}
getTo() public
getTo()
Gets "to" address. {@see \Cake\Mailer\Message::getTo()}
getTransport() public
getTransport()
Gets the transport.
Returns
\Cake\Mailer\AbstractTransportimplementedEvents() public
implementedEvents()
Implemented events.
Returns
arrayloadModel() public
loadModel(?string $modelClass, ?string $modelType)
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\RepositoryInterfaceThe model instance created.
Throws
Cake\Datasource\Exception\MissingModelExceptionIf the model class cannot be found.
UnexpectedValueExceptionIf $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty.
logDelivery() protected
logDelivery(array $contents)
Log the email message delivery.
Parameters
-
array$contents The content with 'headers' and 'message' keys.
modelFactory() public
modelFactory(string $type, mixed $factory)
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|\Cake\Datasource\Locator\LocatorInterface$factory The factory function used to create instances.
parseDsn() public static
parseDsn(string $dsn)
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
arrayThe configuration array to be stored after parsing the DSN
Throws
InvalidArgumentExceptionIf not passed a string, or passed an invalid string
render() public
render(string $content)
Render content and set message body.
Parameters
-
string$content optional Content.
Returns
$thisreset() public
reset()
Reset all the internal variables to be able to send out a new email.
Returns
$thisrestore() protected
restore()
Restore message, renderer, transport instances to state before an action was run.
Returns
$thissend() public
send(?string $action, array $args, array $headers)
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
arrayThrows
Cake\Mailer\Exception\MissingActionExceptionBadMethodCallExceptionset() public
set(mixed $key, mixed $value)
Sets email view vars.
Parameters
-
string|array$key Variable name or hash of view variables.
-
mixed$value optional View variable value.
Returns
$thissetAttachments() public
setAttachments(mixed $attachments)
Add attachments to the email message. {@see \Cake\Mailer\Message::setAttachments()}
Parameters
-
mixed$attachments
setBcc() public
setBcc(mixed $email, mixed $name)
Sets "bcc" address. {@see \Cake\Mailer\Message::setBcc()}
Parameters
-
mixed$email -
mixed$name
setCc() public
setCc(mixed $email, mixed $name)
Sets "cc" address. {@see \Cake\Mailer\Message::setCc()}
Parameters
-
mixed$email -
mixed$name
setCharset() public
setCharset(mixed $charset)
Charset setter. {@see \Cake\Mailer\Message::setCharset()}
Parameters
-
mixed$charset
setConfig() public static
setConfig(mixed $key, mixed $config)
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.
Throws
BadMethodCallExceptionWhen trying to modify an existing config.
LogicExceptionWhen trying to store an invalid structured config array.
setDomain() public
setDomain(mixed $domain)
Sets domain. {@see \Cake\Mailer\Message::setDomain()}
Parameters
-
mixed$domain
setDsnClassMap() public static
setDsnClassMap(array $map)
Updates the DSN class map for this class.
Parameters
-
string[]$map Additions/edits to the class map to apply.
setEmailFormat() public
setEmailFormat(mixed $format)
Sets email format. {@see \Cake\Mailer\Message::getHeaders()}
Parameters
-
mixed$format
setFrom() public
setFrom(mixed $email, mixed $name)
Sets "from" address. {@see \Cake\Mailer\Message::setFrom()}
Parameters
-
mixed$email -
mixed$name
setHeaderCharset() public
setHeaderCharset(mixed $charset)
HeaderCharset setter. {@see \Cake\Mailer\Message::setHeaderCharset()}
Parameters
-
mixed$charset
setHeaders() public
setHeaders(array $headers)
Sets headers for the message. {@see \Cake\Mailer\Message::setHeaders()}
Parameters
-
array$headers
setLogConfig() protected
setLogConfig(mixed $log)
Set logging config.
Parameters
-
string|array|true$log Log config.
setMessage() public
setMessage(\Cake\Mailer\Message $message)
Set message instance.
Parameters
-
\Cake\Mailer\Message$message Message instance.
Returns
$thissetMessageId() public
setMessageId(mixed $message)
Sets message ID. {@see \Cake\Mailer\Message::setMessageId()}
Parameters
-
mixed$message
setModelType() public
setModelType(string $modelType)
Set the model type to be used by this class
Parameters
-
string$modelType The model type
Returns
$thissetProfile() public
setProfile(mixed $config)
Sets the configuration profile to use for this instance.
Parameters
-
string|array$config String with configuration name, or an array with config.
Returns
$thissetReadReceipt() public
setReadReceipt(mixed $email, mixed $name)
Sets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::setReadReceipt()}
Parameters
-
mixed$email -
mixed$name
setRenderer() public
setRenderer(\Cake\Mailer\Renderer $renderer)
Set email renderer.
Parameters
-
\Cake\Mailer\Renderer$renderer Render instance.
Returns
$thissetReplyTo() public
setReplyTo(mixed $email, mixed $name)
Sets "Reply-To" address. {@see \Cake\Mailer\Message::setReplyTo()}
Parameters
-
mixed$email -
mixed$name
setReturnPath() public
setReturnPath(mixed $email, mixed $name)
Sets return path. {@see \Cake\Mailer\Message::setReturnPath()}
Parameters
-
mixed$email -
mixed$name
setSender() public
setSender(mixed $email, mixed $name)
Sets "sender" address. {@see \Cake\Mailer\Message::setSender()}
Parameters
-
mixed$email -
mixed$name
setSubject() public
setSubject(mixed $subject)
Sets subject. {@see \Cake\Mailer\Message::setSubject()}
Parameters
-
mixed$subject
setTo() public
setTo(mixed $email, mixed $name)
Sets "to" address. {@see \Cake\Mailer\Message::setTo()}
Parameters
-
mixed$email -
mixed$name
setTransport() public
setTransport(mixed $name)
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
$thisThrows
LogicExceptionWhen the chosen transport lacks a send method.
InvalidArgumentExceptionWhen $name is neither a string nor an object.
setViewVars() public
setViewVars(mixed $key, mixed $value)
Sets email view vars.
Parameters
-
string|array$key Variable name or hash of view variables.
-
mixed$value optional View variable value.
Returns
$thisviewBuilder() public
viewBuilder()
Get the view builder.
Returns
\Cake\View\ViewBuilderProperty Detail
$_config protected static
Configuration sets.
Type
array$_dsnClassMap protected static
Mailer driver class map.
Type
array$_modelFactories protected
A list of overridden model factory functions.
Type
(callable|\Cake\Datasource\Locator\LocatorInterface)[]$_modelType protected
The model type to use.
Type
string$clonedInstances protected
Hold message, renderer and transport instance for restoring after runnning a mailer action.
Type
array$logConfig protected
Type
array|null$message protected
Message instance.
Type
\Cake\Mailer\Message$messageClass protected
Message class name.
Type
string$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$name public static
Mailer's name.
Type
string$renderer protected
Email Renderer
Type
\Cake\Mailer\Renderer|null$transport protected
The transport instance to use for sending mail.
Type
\Cake\Mailer\AbstractTransport|null
© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.1/class-Cake.Mailer.Mailer.html