Using Sendgrid or Mandrill to send emails in a Codeigniter Application

By default most websites send the emails via their own email servers and it just gets delivered fine using the php email functionality or by using the codeigniter email library.

But there are several web applications including e-commerce or any management application where email plays a very important role , so you need to make sure the email is received by your customer fine without any bounce or spam.There are transactional email services available like Mandrill by Mailchimp , Postmarkapp and Sendgrid.

I use mainly Mandrill and Mailchimp for most of my web applications.The benefits of using a transactional email service is that the email will be delivered just fine without any worries and you can also track the open rate and clicks.Mandrill gives you 12,000 free emails per month .

Integrating in Codeigniter

Codeigniter email library helps you send emails and it can be configured on the fly.You just need to send the smtp settings to use the mandrill or sendgrid service.Lets have a look at the examples.


$this->load->library('email');
$this->email->initialize(array(
              'protocol' => 'smtp',
              'smtp_host' => 'smtp.mandrillapp.com',
              'smtp_user' => 'mandrill username',
              'smtp_pass' => 'API KEY',
              'smtp_port' => 587,
              'mailtype' => 'html',
              'crlf' => "rn",
              'newline' => "rn"
           ));

$this->email->from('from email', 'from name');
$this->email->to('reciever email');
$this->email->subject('The Subject');
$this->email->message($this->load->view('email_view',TRUE));//Load a view into email body
$this->email->send();
echo $this->email->print_debugger(); //For Debugging Purpose

The TRUE parameter in the load view returns the view as a string rather than sending it to your browser.


$this->load->library('email');
$this->email->initialize(array(
       'protocol' => 'smtp',
       'smtp_host' => 'smtp.sendgrid.net',
       'smtp_user' => 'sendgrid username',
       'smtp_pass' => 'sendgrid password',
       'smtp_port' => 25,
       'crlf' => "rn",
       'newline' => "rn"
));

Sending emails from localhost

To test your emails via codeigniter and mandrill/sendgrid service download this tool.