15 December 2016

Resolving issues using Google's smtp email with Codeigniter

So this took me days to figure out, so hence a blog-post.

I’ve been looking for an easy way to test apps that use email locally. Using an online smtp service like gmail is in my opinion, much easier than setting up a local mail server. The natural choice for me was gmail since I have already created some test accounts for development there (It’s best not to mix personal and dev accounts for reasons which will be apparent later on). However, I did run into a couple of issues trying this with CodeIgniter.

Issue 1.

With your dev account open, go here and turn on access for less secure apps. Thanks to http://www.wpsitecare.com/gmail-smtp-settings/ for that.

Issue 2.

After loading CodeIgniter’s email library, the following line is essential to send email

$this->email->set_newline("\r\n"); // in the controller

or add the equivalent to the email config file (see example below)

$config['newline'] = "\r\n"; // essential to use double quotes here!!!

(Update: I’ve found more info on that issue here).

After checking off these two points, you can now proceed to send smtp email locally.

Here is a quick example

In application/config, create a file called email.php (it will be automatically recognised by CodeIgniter). Add the following

<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

// SMTP config
$config['mailtype'] = 'html'; // default is text
$config['protocol'] = 'smtp';
$config['charset'] = 'utf-8';
//$config['newline'] = "\r\n"; // essential to use double quotes here!!!
$config['smtp_host'] = 'ssl://smtp.gmail.com';
$config['smtp_port'] = 465;
$config['smtp_user'] = 'your_dev_email@gmail.com';
$config['smtp_pass'] = 'Your_Password';

In your controller, add

$this->email->set_newline("\r\n"); // will fail without this line!!!

$this->email->from('your_dev_email@gmail.com', 'Your_Name');
$this->email->subject('Email Test');
$this->email->message('Test_mail controller.');

  $data['message'] = "Mail sent...";
else {
    $data['message'] = "Sorry Unable to send email...";

$this->load->view('your_view', $data);

Then check the output in your_view by echoing the $message variable, and of course check your email ;)

No comments:

Post a Comment