Skip to contentSkip to navigationSkip to topbar
Rate this page:

CakePHP


CakePHP comes with an email library that already supports SMTP. For more information check out the CakePHP documentation page(link takes you to an external page). This example shows how to send an email with both HTML and text bodies.

In app/views/layouts/ you need to define the layout of your text and HTML emails:


_10
email/
_10
html/
_10
default.ctp
_10
text/
_10
default.ctp

In app/views/layouts/email/text/default.ctp add:


_10
<!--?php echo $content_for_layout; ?-->

and in app/views/layouts/email/html/default.ctp add:


_10
<!--?php echo $content_for_layout; ?-->

Then create the template for your emails. In this example we created templates for a registration email with the following structure:


_10
app/
_10
views/
_10
elements/
_10
email/
_10
text/
_10
registration.ctp
_10
html/
_10
registration.ctp

In app/views/elements/email/text/registration.ctp add:


_10
Dear <!--?php echo $name ?-->,
_10
Thank you for registering. Please go to http://domain.com to finish your registration.

and in app/views/layouts/email/html/default.ctp add:


_10
Dear <!--?php echo $name ?-->,
_10
Thank you for registering. Please go to <a href="http://domain.com">here</a> to finish your registration.

In your controller enable the email component:


_10
<!--?php var $components = array('Email'); ?-->

Then anywhere in your controller you can do something like the following to send an email: (make sure to replace your own sendgrid_username / sendgrid_api_key details, better to make them constant)


_19
<?php
_19
$this->Email->smtpOptions = array(
_19
'port'=>'587',
_19
'timeout'=>'30',
_19
'host' => 'smtp.sendgrid.net',
_19
'username'=>'sendgrid_username',
_19
'api_key'=>'sendgrid_api_key',
_19
'client' => 'yourdomain.com'
_19
);
_19
_19
$this->Email->delivery = 'smtp';
_19
$this->Email->from = 'Your Name ';
_19
$this->Email->to = 'Recipient Name ';
_19
$this->set('name', 'Recipient Name');
_19
$this->Email->subject = 'This is a subject';
_19
$this->Email->template = 'registration';
_19
$this->Email->sendAs = 'both';
_19
$this->Email->send();
_19
?>


Rate this page: