Sending Emails in CakePHP with Example

Author - Sahil Bhalla
27.11.2018
|
0 Comments
||

What support/library is there in CakePHP for sending emails and how to use it?

In CakePHP3, there are Transport and Email classes available under Cake/Network/Email namespace that are used for sending emails. After an update in the version 3.1 email functionality has been updated to Cake/Mailer namespace.

Configuring email in cakephp

The Transport Class is configured inside config.php and it allows you to keep configuration data out of your application code and makes deployment simpler as you can simply change the configuration data in config file. A sample transport configuration looks like:

use Cake\Mailer\Email;
// Sample Mail configuration 
Email::configTransport('default', [
    'className' => 'Mail' ]);

// Sample SMTP configuration
Email::configTransport('gmail', [
    'host' => 'ssl://smtp.gmail.com',
    'port' => 495,
    'username' => 'my@gmail.com',
    'password' => 'password',
    'className' => 'Smtp'
]);

Email is the name of the class that is included in the controller. Using this class we can send email from any place inside the application. After this class is loaded an object for the same is created. There are various methods that are implemented in this class for sending an email. Some of them are written below:

1. from() -> includes email or array of sender’s email
2. to() -> includes email or array of receiver’s email
3. cc() -> includes email or array of carbon copy
4. subject() -> subject of the message
5. attachments() -> files to attach
6. message() -> body of the email
7. replyTo() -> includes email or array of email

Example:-

$email = new Email('default');
$email->from(['me@example.com' => 'My Site'])
    ->to('you@example.com')
    ->subject('About')
    ->send('My message');

CakePHP provides a way to send emails using view layer. The template for the email reside in a Email folder in Template directory. Email views can also use layouts and elements just like normal views.

Example:-

$email->template('welcome', 'fancy')
    ->emailFormat('html')
    ->to('bob@example.com')
    ->from('app@domain.com')
    ->send();

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *