Thursday, January 21, 2010

A solution for e-mail handling in CakePHP

The emailComponent (cake\libs\controller\components\email.php) is a way for you to using the same concepts of layouts and view ctp files to send formated messages as text, html or both. It supports sending via the built in mail functions of PHP, via smtp server or a debug mode where it writes the message out to a session flash message. It also supports file attachments.
Implements it in three easy Steps
1. Controller (STEP 1)

In your controller you need to add the component to your $components array or add a $components array to your controller like:
1. 2. var $components = array('Email');
3. ?>

In this example we will set up a private method to handle sending the email messages to a user identified by an $id. In our controller (let's use the User controller in this example)

1. 2. function _sendNewUserMail($id) {
3. $User = $this->User->read(null,$id);
4. $this->Email->to = $User['User']['email'];
5. $this->Email->bcc = array('anuragtrivediphp@gmail.com');
6. $this->Email->subject = 'Welcome to cakePHP email handling functionally';
7. $this->Email->replyTo = 'anuragtrivediphp @ gmail.com';
8. $this->Email->from = Anurag Blog ';
9. $this->Email->template = ‘contact'; // note no '.ctp'
10. //Send as 'html', 'text' or 'both' (default is 'text')
11. $this->Email->sendAs = 'both'; // because we like to send pretty mail
12. //Set view variables as normal
13. $this->set('User', $User);
14. //Do not pass any args to send()
15. $this->Email->send();
16. }
17. ?>

You have sent a message; you could call this from another method like
1. $this->_sendNewUserMail( $this->User->id );

2. Setting up the Layouts (Step 2)
To use both text and html mailing message you need to create layout files for them, just like in setting up your default layouts for the display of your views in a browser, you need to set up default layouts for your email messages. In the app/views/layouts/ directory you need to set up (at a minimum) the following structure
email/
html/
default.ctp
text/
default.ctp
These are the files that hold the layout templates for your default messages. Some example content is below
email/text/default.ctp
1.

email/html/default.ctp
1.
2. < html >
3. < body >
4.
5. < /body >
6. < /html >

3. Setup an email element for the message body
(Step 3)
In the app/views/elements/email/ directory you need to set up folders for text and html unless you plan to just send one or the other. In each of these folders you need to create templates for both types of messages referring to the content that you send to the view either by using $this->set() or using the $contents parameter of the send() method. Some simple examples are shown below. For this example we will call the templates
contact.ctp
1.Dear ,

In html

Dear ,< br />
Thank you for your interest.

No comments:

Post a Comment