Leveraging HTML Emails in CodeIgniter

Hey friends..here I come with my new tipĀ “Leaveraging HTML Emails in CodeIgniter”. Well I know most of the coder already know how to take advantage of html templates in CodeIgniter for sending emails but I think this tip can help someone to find their solution šŸ™‚

Need to send HTML emails through your website is omnipresent, be it a newsletter or some auto generated welcome message. Usually we write our hard coded corresponding html in theĀ message parameter of our email object.

Well, I would say the above method is pretty ugly. The following tip is not quite a trick but merely a way to take advantage of some CodeIgniter functionality where it makes sense.

Being a developer I personally prefer to use this approach to send a newsletter,Ā and several other HTML emails, and using templates will significantly ease up the process.

Create a emails folder inside your views ( home dir/application/views)Ā and place any HTML email you’d like to send inside it, with the corresponding structure to be rendered by email clients. And now, in the method where you shoot off the emails, you can use the following code:

public function send_mail() {
$this->load->library( 'email' );
$this->email->from( 'sender@gmail.com', 'Sender Name' );
$this->email->to( 'reciever@gmail.com' );
$this->email->subject( 'Subject of the email' );
$this->email->message( $this->load->view( 'emails/message', $data, true ) );

A couple of important things to keep in mind when using this technique:

  • The email library must be set up to be able to send HTML emails
  • The data object used when loading the view should contain the options used in the view
  • With this approach, we’re using the built-in functionality of retrieving the content of a view file instead of sending it to the output class by setting the third parameter to true when loading the view.

Conclusion:-Ā I hope you’ve found this tip useful. If you have any question / doubt or any suggestion then please feel free to write your comment below or send me a personal message from here.

Leave a Reply

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