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:

1
email/
2
html/
3
default.ctp
4
text/
5
default.ctp

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

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

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

<!--?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:

1
app/
2
views/
3
elements/
4
email/
5
text/
6
registration.ctp
7
html/
8
registration.ctp

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

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

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

1
Dear <!--?php echo $name ?-->,
2
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:

<!--?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)

1
<?php
2
$this->Email->smtpOptions = array(
3
'port'=>'587',
4
'timeout'=>'30',
5
'host' => 'smtp.sendgrid.net',
6
'username'=>'sendgrid_username',
7
'api_key'=>'sendgrid_api_key',
8
'client' => 'yourdomain.com'
9
);
10
11
$this->Email->delivery = 'smtp';
12
$this->Email->from = 'Your Name ';
13
$this->Email->to = 'Recipient Name ';
14
$this->set('name', 'Recipient Name');
15
$this->Email->subject = 'This is a subject';
16
$this->Email->template = 'registration';
17
$this->Email->sendAs = 'both';
18
$this->Email->send();
19
?>

Rate this page: