Quantcast
Channel: BIOSTALL » PHP
Viewing all articles
Browse latest Browse all 57

Resolving Error with Sending Emails via SMTP Using CodeIgniter

$
0
0

When sending emails using the CodeIgniter Email Class, I’ve always just kept the protocol as ‘mail‘ meaning emails get sent using the standard PHP mail() function.

Recently however, on an application we had been developing, emails were a critical part of the system. We had to give them the best chance of being received successfully, and do our best to ensure they didn’t get rejected by spam filters. As a result we turned to sending emails via the SMTP protocol.

Fortunately, CodeIgniter’s Email Class can accept some additional configuration options to get this setup easily. This looks like something like so:

$this->load->library('email');

$config = array();
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'xxx';
$config['smtp_user'] = 'xxx';
$config['smtp_pass'] = 'xxx';
$config['smtp_port'] = 25;
$this->email->initialize($config);

Oddly, when we’d performed the above the change and began sending emails we saw the following error from the debugger:

Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.

We tried to use different encoding, different subjects, recipients, senders, basically everything but we continued to get the error message above.

The Solution

After a fair bit of research we discovered that the issue was to do with line breaks and the way in which the SMTP host interprets them. The default new line character is \n, whereas the SMTP server is expecting \r\n. It never finds that so thinks that it never reached the end, ultimately causing a timeout.

Fortunately, changing this is simple. We can simply add the following after our call to the ‘initialize()‘ function:

$this->email->set_newline("\r\n");

Our final code then looks something like so:

$this->load->library('email');

$config = array();
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'xxx';
$config['smtp_user'] = 'xxx';
$config['smtp_pass'] = 'xxx';
$config['smtp_port'] = 25;
$this->email->initialize($config);

$this->email->set_newline("\r\n");

// Send email(s) here...

I’m not sure if this is only the case with certain SMTP servers. It solved it for us however and hope it proves helpful if you’re encountering the same error.


Viewing all articles
Browse latest Browse all 57

Latest Images

Trending Articles



Latest Images