Warning
Before version 3.1, the Email
and Transport
classes were underthe Cake\Network\Email
namespace instead of the Cake\Mailer
namespace.
- class
Cake\Mailer\
Email
(mixed $profile = null) Email
is a new class to send email. With thisclass you can send email from any place inside of your application.
Basic Usage
First of all, you should ensure the class is loaded:
- use Cake\Mailer\Email;
After you’ve loaded Email
, you can send an email with the following:
- $email = new Email('default');
- $email->from(['me@example.com' => 'My Site'])
- ->to('you@example.com')
- ->subject('About')
- ->send('My message');
Since Email
’s setter methods return the instance of the class, you are able to set its properties with method chaining.
Email
has several methods for defining recipients - to()
, cc()
,bcc()
, addTo()
, addCc()
and addBcc()
. The main difference beingthat the first three will overwrite what was already set and the latter will justadd more recipients to their respective field:
- $email = new Email();
- $email->to('to@example.com', 'To Example');
- $email->addTo('to2@example.com', 'To2 Example');
- // The email's To recipients are: to@example.com and to2@example.com
- $email->to('test@example.com', 'ToTest Example');
- // The email's To recipient is: test@example.com
Deprecated since version 3.4.0: Use setFrom()
, setTo()
, setCc()
, setBcc()
and setSubject()
instead.
Choosing the Sender
When sending email on behalf of other people, it’s often a good idea to define theoriginal sender using the Sender header. You can do so using sender()
:
- $email = new Email();
- $email->sender('app@example.com', 'MyApp emailer');
Note
It’s also a good idea to set the envelope sender when sending mail on anotherperson’s behalf. This prevents them from getting any messages aboutdeliverability.
Deprecated since version 3.4.0: Use setSender()
instead.
Configuration
Configuration for Email
defaults is created using config()
andconfigTransport()
. You should put your email presets in theconfig/app.php file. The config/app.default.php file is anexample of this file. It is not required to define email configuration inconfig/app.php. Email
can be used without it and use the respectivemethods to set all configurations separately or load an array of configs.
By defining profiles and transports, you can keep your application code free ofconfiguration data, and avoid duplication that makes maintenance and deploymentmore difficult.
To load a predefined configuration, you can use the profile()
method or pass itto the constructor of Email
:
- $email = new Email();
- $email->profile('default');
- // Or in constructor
- $email = new Email('default');
Instead of passing a string which matches a preset configuration name, you canalso just load an array of options:
- $email = new Email();
- $email->profile(['from' => 'me@example.org', 'transport' => 'my_custom']);
- // Or in constructor
- $email = new Email(['from' => 'me@example.org', 'transport' => 'my_custom']);
Changed in version 3.1: The default
email profile is automatically set when an Email
instance is created.
Deprecated since version 3.4.0: Use setProfile()
instead of profile()
.
Configuring Transports
- static
Cake\Mailer\Email::
configTransport
($key, $config) - Email messages are delivered by transports. Different transports allow you tosend messages via PHP’s
mail()
function, SMTP servers, or not at all whichis useful for debugging. Configuring transports allows you to keep configurationdata out of your application code and makes deployment simpler as you can simplychange the configuration data. An example transport configuration looks like:
- use Cake\Mailer\Email;
- use Cake\Mailer\TransportFactory;
- // Sample Mail configuration
- // Prior to 3.7.0 use Email::configTransport()
- TransportFactory::setConfig('default', [
- 'className' => 'Mail'
- ]);
- // Sample SMTP configuration.
- TransportFactory::setConfig('gmail', [
- 'host' => 'ssl://smtp.gmail.com',
- 'port' => 465,
- 'username' => 'my@gmail.com',
- 'password' => 'secret',
- 'className' => 'Smtp'
- ]);
You can configure SSL SMTP servers, like Gmail. To do so, put the ssl://
prefix in the host and configure the port value accordingly. You can alsoenable TLS SMTP using the tls
option:
- use Cake\Mailer\Email;
- use Cake\Mailer\TransportFactory;
- TransportFactory::setConfig('gmail', [
- 'host' => 'smtp.gmail.com',
- 'port' => 587,
- 'username' => 'my@gmail.com',
- 'password' => 'secret',
- 'className' => 'Smtp',
- 'tls' => true
- ]);
The above configuration would enable TLS communication for email messages.
Warning
You will need to have access for less secure apps enabled in your Googleaccount for this to work:Allowing less secure apps to access youraccount.
Note
Note
To use SSL + SMTP, you will need to have the SSL configured in your PHPinstall.
Configuration options can also be provided as a DSN string. This isuseful when working with environment variables or PaaS providers:
- TransportFactory::setConfig('default', [
- 'url' => 'smtp://my@gmail.com:secret@smtp.gmail.com:587?tls=true',
- ]);
- // Prior to 3.7.0 use
- Email::configTransport('default', [
- 'url' => 'smtp://my@gmail.com:secret@smtp.gmail.com:587?tls=true',
- ]);
When using a DSN string you can define any additional parameters/options asquery string arguments.
- static
Cake\Mailer\Email::
dropTransport
($key) - Once configured, transports cannot be modified. In order to modify a transportyou must first drop it and then reconfigure it.
Configuration Profiles
Defining delivery profiles allows you to consolidate common email settings intore-usable profiles. Your application can have as many profiles as necessary. Thefollowing configuration keys are used:
'from'
: Email or array of sender. SeeEmail::from()
.'sender'
: Email or array of real sender. SeeEmail::sender()
.'to'
: Email or array of destination. SeeEmail::to()
.'cc'
: Email or array of carbon copy. SeeEmail::cc()
.'bcc'
: Email or array of blind carbon copy. SeeEmail::bcc()
.'replyTo'
: Email or array to reply the e-mail. SeeEmail::replyTo()
.'readReceipt'
: Email address or an array of addresses to receive thereceipt of read. SeeEmail::readReceipt()
.'returnPath'
: Email address or an array of addresses to return if havesome error. SeeEmail::returnPath()
.'messageId'
: Message ID of e-mail. SeeEmail::messageId()
.'subject'
: Subject of the message. SeeEmail::subject()
.'message'
: Content of message. Do not set this field if you are using rendered content.'priority'
: Priority of the email as numeric value (usually from 1 to 5 with 1 being the highest).'headers'
: Headers to be included. SeeEmail::headers()
.'viewRender'
: If you are using rendered content, set the view classname.SeeEmail::viewRender()
.'template'
: If you are using rendered content, set the template name. SeeEmail::template()
.'theme'
: Theme used when rendering template. SeeEmail::theme()
.'layout'
: If you are using rendered content, set the layout to render. Ifyou want to render a template without layout, set this field to null. SeeEmail::template()
.'viewVars'
: If you are using rendered content, set the array withvariables to be used in the view. SeeEmail::setViewVars()
.'attachments'
: List of files to attach. SeeEmail::attachments()
.'emailFormat'
: Format of email (html, text or both). SeeEmail::emailFormat()
.'transport'
: Transport configuration name. SeeMailer\Email::configTransport()
.'log'
: Log level to log the email headers and message.true
will useLOG_DEBUG. See also Using Levels.'helpers'
: Array of helpers used in the email template.Email::helpers()
.
All these configurations are optional, except'from'
.
Note
The values of above keys using Email or array, like from, to, cc, etc will be passedas first parameter of corresponding methods. The equivalent for:Email::from('my@example.com', 'My Site')
would be defined as 'from' => ['my@example.com' => 'My Site']
in your config
Setting Headers
In Email
you are free to set whatever headers you want. When migratingto use Email, do not forget to put the X-
prefix in your headers.
See Email::headers()
and Email::addHeaders()
Deprecated since version 3.4.0: Use setHeaders()
instead of headers()
.
Sending Templated Emails
Emails are often much more than just a simple text message. In orderto facilitate that, CakePHP provides a way to send emails using CakePHP’sview layer.
The templates for emails reside in a special folder in your application’sTemplate
directory called Email
. Email views can also use layoutsand elements just like normal views:
- $email = new Email();
- ->template('welcome', 'fancy')
- ->emailFormat('html')
- ->to('bob@example.com')
- ->from('app@domain.com')
- ->send();
The above would use src/Template/Email/html/welcome.ctp for the viewand src/Template/Layout/Email/html/fancy.ctp for the layout. You cansend multipart templated email messages as well:
- $email = new Email();
- ->template('welcome', 'fancy')
- ->emailFormat('both')
- ->to('bob@example.com')
- ->from('app@domain.com')
- ->send();
This would use the following template files:
- src/Template/Email/text/welcome.ctp
- src/Template/Layout/Email/text/fancy.ctp
- src/Template/Email/html/welcome.ctp
- src/Template/Layout/Email/html/fancy.ctp
When sending templated emails you have the option of sending eithertext
,html
orboth
.
You can set view variables with Email::setViewViars()
:
- $email = new Email('templated');
- $email->setViewVars(['value' => 12345]);
In your email templates you can use these with:
- <p>Here is your value: <b><?= $value ?></b></p>
You can use helpers in emails as well, much like you can in normal template files.By default only the HtmlHelper
is loaded. You can load additionalhelpers using the helpers()
method:
- $email->helpers(['Html', 'Custom', 'Text']);
When setting helpers be sure to include ‘Html’ or it will be removed from thehelpers loaded in your email template.
If you want to send email using templates in a plugin you can use the familiarplugin syntax to do so:
- $email = new Email();
- $email->template('Blog.new_comment', 'Blog.auto_message');
The above would use template and layout from the Blog plugin as an example.
In some cases, you might need to override the default template provided by plugins.You can do this using themes by telling Email to use appropriate theme usingEmail::theme()
method:
- $email = new Email();
- $email->template('Blog.new_comment', 'Blog.auto_message');
- $email->theme('TestTheme');
This allows you to override the new_comment
template in your theme withoutmodifying the Blog plugin. The template file needs to be created in thefollowing path:src/Template/Plugin/TestTheme/Plugin/Blog/Email/text/new_comment.ctp.
Deprecated since version 3.4.0: Use viewBuilder()->setTemplate()
instead of template()
. UseviewBuilder()->setLayout()
instead of the layout argument oftemplate()
. Use viewBuilder()->setTheme()
instead of theme()
.
Sending Attachments
Cake\Mailer\Email::
attachments
($attachments)You can attach files to email messages as well. There are a fewdifferent formats depending on what kind of files you have, and howyou want the filenames to appear in the recipient’s mail client:
String:
$email->attachments('/full/file/path/file.png')
will attach thisfile with the name file.png.Array:
$email->attachments(['/full/file/path/file.png'])
will havethe same behavior as using a string.Array with key:
$email->attachments(['photo.png' => '/full/some_hash.png'])
willattach some_hash.png with the name photo.png. The recipient will seephoto.png, not some_hash.png.Nested arrays:
- $email->attachments([
- 'photo.png' => [
- 'file' => '/full/some_hash.png',
- 'mimetype' => 'image/png',
- 'contentId' => 'my-unique-id'
- ]
- ]);
The above will attach the file with different mimetype and with customContent ID (when set the content ID the attachment is transformed to inline).The mimetype and contentId are optional in this form.
4.1. When you are using the contentId
, you can use the file in the HTMLbody like <img src="cid:my-content-id">
.
4.2. You can use the contentDisposition
option to disable theContent-Disposition
header for an attachment. This is useful whensending ical invites to clients using outlook.
4.3 Instead of the file
option you can provide the file contents asa string using the data
option. This allows you to attach files withoutneeding file paths to them.
Deprecated since version 3.4.0: Use setAttachments()
instead of attachments()
.
Using Transports
Transports are classes designed to send the e-mail over some protocol or method.CakePHP supports the Mail (default), Debug and SMTP transports.
To configure your method, you must use the Cake\Mailer\Email::transport()
method or have the transport in your configuration:
- $email = new Email();
- // Use a named transport already configured using Email::configTransport()
- $email->transport('gmail');
- // Use a constructed object.
- $transport = new DebugTransport();
- $email->transport($transport);
Deprecated since version 3.4.0: Use setTransport()
instead of transport()
.
Creating Custom Transports
You are able to create your custom transports to integrate with others emailsystems (like SwiftMailer). To create your transport, first create the filesrc/Mailer/Transport/ExampleTransport.php (where Example is the name of yourtransport). To start off your file should look like:
- namespace App\Mailer\Transport;
- use Cake\Mailer\AbstractTransport;
- use Cake\Mailer\Email;
- class ExampleTransport extends AbstractTransport
- {
- public function send(Email $email)
- {
- // Do something.
- }
- }
You must implement the method send(Email $email)
with your custom logic.Optionally, you can implement the config($config)
method. config()
iscalled before send() and allows you to accept user configurations. By default,this method puts the configuration in protected attribute $_config
.
If you need to call additional methods on the transport before send, you can useCake\Mailer\Email::getTransport()
to get an instance of the transport object.Example:
- $yourInstance = $email->getTransport()->transportClass();
- $yourInstance->myCustomMethod();
- $email->send();
Relaxing Address Validation Rules
Cake\Mailer\Email::
emailPattern
($pattern)- If you are having validation issues when sending to non-compliant addresses, youcan relax the pattern used to validate email addresses. This is sometimesnecessary when dealing with some ISP’s:
- $email = new Email('default');
- // Relax the email pattern, so you can send
- // to non-conformant addresses.
- $email->emailPattern($newPattern);
Deprecated since version 3.4.0: Use setEmailPattern()
instead of emailPattern()
.
Sending Messages Quickly
Sometimes you need a quick way to fire off an email, and you don’t necessarilywant do setup a bunch of configuration ahead of time.Cake\Mailer\Email::deliver()
is intended for that purpose.
You can create your configuration usingCake\Mailer\Email::config()
, or use an array with alloptions that you need and use the static method Email::deliver()
.Example:
- Email::deliver('you@example.com', 'Subject', 'Message', ['from' => 'me@example.com']);
This method will send an email to “you@example.com”, from “me@example.com” withsubject “Subject” and content “Message”.
The return of deliver()
is a Cake\Mailer\Email
instance with allconfigurations set. If you do not want to send the email right away, and wishto configure a few things before sending, you can pass the 5th parameter asfalse
.
The 3rd parameter is the content of message or an array with variables (whenusing rendered content).
The 4th parameter can be an array with the configurations or a string with thename of configuration in Configure
.
If you want, you can pass the to, subject and message as null and do allconfigurations in the 4th parameter (as array or using Configure
).Check the list of configurations to see all accepted configs.
Sending Emails from CLI
When sending emails within a CLI script (Shells, Tasks, …) you should manuallyset the domain name for Email to use. It will serve as the host name for themessage id (since there is no host name in a CLI environment):
- $email->domain('www.example.org');
- // Results in message ids like ``<UUID@www.example.org>`` (valid)
- // Instead of `<UUID@>`` (invalid)
A valid message id can help to prevent emails ending up in spam folders.
Deprecated since version 3.4.0: Use setDomain()
instead of domain()
.
Creating Reusable Emails
New in version 3.1.0.
Mailers allow you to create reusable emails throughout your application. Theycan also be used to contain multiple email configurations in one location. Thishelps keep your code DRYer and keeps email configuration noise out of otherareas in your application.
In this example we will be creating a Mailer
that contains user-relatedemails. To create our UserMailer
, create the filesrc/Mailer/UserMailer.php. The contents of the file should look like thefollowing:
- namespace App\Mailer;
- use Cake\Mailer\Mailer;
- class UserMailer extends Mailer
- {
- public function welcome($user)
- {
- $this
- ->to($user->email)
- ->subject(sprintf('Welcome %s', $user->name))
- ->template('welcome_mail', 'custom'); // By default template with same name as method name is used.
- }
- public function resetPassword($user)
- {
- $this
- ->to($user->email)
- ->subject('Reset password')
- ->set(['token' => $user->token]);
- }
- }
In our example we have created two methods, one for sending a welcome email, andanother for sending a password reset email. Each of these methods expect a userEntity
and utilizes its properties for configuring each email.
We are now able to use our UserMailer
to send out our user-related emailsfrom anywhere in our application. For example, if we wanted to send our welcomeemail we could do the following:
- namespace App\Controller;
- use Cake\Mailer\MailerAwareTrait;
- class UsersController extends AppController
- {
- use MailerAwareTrait;
- public function register()
- {
- $user = $this->Users->newEntity();
- if ($this->request->is('post')) {
- $user = $this->Users->patchEntity($user, $this->request->getData())
- if ($this->Users->save($user)) {
- $this->getMailer('User')->send('welcome', [$user]);
- }
- }
- $this->set('user', $user);
- }
- }
If we wanted to completely separate sending a user their welcome email from ourapplication’s code, we can have our UserMailer
subscribe to theModel.afterSave
event. By subscribing to an event, we can keep ourapplication’s user-related classes completely free of email-related logic andinstructions. For example, we could add the following to our UserMailer
:
- public function implementedEvents()
- {
- return [
- 'Model.afterSave' => 'onRegistration'
- ];
- }
- public function onRegistration(Event $event, EntityInterface $entity, ArrayObject $options)
- {
- if ($entity->isNew()) {
- $this->send('welcome', [$entity]);
- }
- }
The mailer object could now be registered as an event listener, and theonRegistration()
method would be invoked every time the Model.afterSave
event would be fired. For information on how to register event listener objects,please refer to the Registering Listeners documentation.
Testing Email
To test email, add Cake\TestSuite\EmailTrait
to your test case.The EmailTrait
provides your test case with a collection of assertionsthat you can perform on any emails sent by the application.
Adding the EmailTrait
to your test case will replace all of your application’semail transports with the Cake\TestSuite\TestEmailTransport
. This transportintercepts emails instead of sending them, and allows you to assert against them.
Add the trait to your test case to start testing emails:
- namespace App\Test\TestCase;
- use Cake\TestSuite\EmailTrait;
- class MyTestCase extends TestCase
- {
- use EmailTrait;
- }
New in version 3.7.0: Cake\TestSuite\EmailTrait
was added.
Assertion methods
The Cake\TestSuite\EmailTrait
trait provides the following assertions:
- // Asserts an expected number of emails were sent
- $this->assertMailCount($count);
- // Asserts that no emails were sent
- $this->assertNoMailSent();
- // Asserts an email was sent to an address
- $this->assertMailSentTo($address);
- // Asserts an email was sent from an address
- $this->assertMailSentFrom($address);
- // Asserts an email contains expected contents
- $this->assertMailContains($contents);
- // Asserts an email contains expected html contents
- $this->assertMailContainsHtml($contents);
- // Asserts an email contains expected text contents
- $this->assertMailContainsText($contents);
- // Asserts an email contains the expected value within an Email getter (e.g., "subject")
- $this->assertMailSentWith($expected, $parameter);
- // Asserts an email at a specific index was sent to an address
- $this->assertMailSentToAt($at, $address);
- // Asserts an email at a specific index was sent from an address
- $this->assertMailSentFromAt($at, $address);
- // Asserts an email at a specific index contains expected contents
- $this->assertMailContainsAt($at, $contents);
- // Asserts an email at a specific index contains expected html contents
- $this->assertMailContainsHtmlAt($at, $contents);
- // Asserts an email at a specific index contains expected text contents
- $this->assertMailContainsTextAt($at, $contents);
- // Asserts an email at a specific index contains the expected value within an Email getter (e.g., "subject")
- $this->assertMailSentWithAt($at, $expected, $parameter);