Thursday 24 November 2011

Send Mail in CakePHP

Following are the steps to send Email in CakePHP. we are using Email component of cake
The first thing you need to do is include the "EmailComponent".

class CommentsController extends AppController  
{  
    var $components = array('Email');  

Now, to send an email, you need two things: email templates (for content) and layouts. Basically, email layout has the same purpose as regular layout - to wrap your content. And templates are where your content will go. This example assumes you're sending an email in both HTML and plain text format.

Location of your layouts and templates are as follows:
/app/views/layouts/email/html/default.ctp
/app/views/layouts/email/text/default.ctp
/app/views/elements/email/html/my_template.ctp
/app/views/elements/email/text/my_template.ctp

..Layout
// /app/views/layouts/email/html/default.ctp
<div> 
<?php echo $content_for_layout; ?>  
<br />  
Thanks & regards
admin
</div>


..Template file
// /app/views/elements/email/html/my_template.ctp  

<p>Dear <?php echo $email_user; ?>,  
<br /><br />  
i will be there, this is my message.  
</p> 
Now, all that remains is to glue all that up with your controller, setting up EmailComponent properties and variables. Setting variables for email templates works the same as setting variables for your view.

$this->Email->reset();  
$this->Email->sendAs = 'both'; // both = html + plain text  
$this->Email->to = 'sam@yahoo.com';  
$this->Email->from = 'admin@example.com';  
$this->Email->replyTo = 'admin@example.com';  
$this->Email->subject = 'your amazing subject here';  
$this->Email->template = 'my_template';  
// of course, if you have multiple layouts, you can change that too  
//$this->Email->layout = 'my_second_layout';  
// this would require you to have my_second_layout  
// ~/app/views/layouts/email/html/my_second_layout.ctp  
// ~/app/views/layouts/email/text/my_second_layout.ctp  
// set some variables for your templates  
$this->set('email_user', $user);   
// uncomment this to debug EmailComponent instead of sending  
//$this->Email->_debug = true;  
$this->Email->send();  




No comments:

Post a Comment