Use SMTP Email Settings from Database in CakePHP 2

Yesterday, one of our client requested to store SMTP email settings in database. Usually, we can do it in the email.php file. However, it is more convenient if we store it in the database and provide a web form to easily change it.

Let say we store the email settings in table called email_settings with model EmailSetting.

One of the way is to retrieve the email settings record in every email sending method you have as per below:

 // get email settings
$EmailSetting = ClassRegistry::init('EmailSetting');
$email_settings = $EmailSetting->findById(1);
$email_setting = $email_settings['EmailSetting'];

and load the SMTP email settings as per below:

if (!empty($email_setting['smtp_host'])) {
 $email->config(array(
    'host' => $email_setting['smtp_host'],
    'port' => $email_setting['smtp_port'],
    'username' => $email_setting['smtp_user'],
    'password' => $email_setting['smtp_password'],
 ));
}

But that way will not promote a code use. After digging CakePHP cookbook, we found out that we can retrieve the email settings in the EmailConfig class (in file /app/Config/email.php). You can just load the SMTP email settings in __construct() function. It’s very convenient and you can easily change it whenever needed.

Here’s the codes:

File:  /app/Config/email.php

class EmailConfig
{
  public function __construct()
  {
      $EmailSetting = ClassRegistry::init('EmailSetting');
      $email_settings = $EmailSetting->findById(1);
      $email_setting = $email_settings['EmailSetting'];

      if (!empty($email_setting['smtp_host'])) {
         $this->default = array(
             'transport' => 'Smtp',
             'from' => $email_setting['from'],
             'host' => $email_setting['smtp_host'],
             'port' => $email_setting['smtp_port'],
             'timeout' => 30,
             'username' => $email_setting['smtp_user'],
             'password' => $email_setting['smtp_password'],
             'client' => null
          );
      }
  }
}

Enjoy!

 

Zharfan Mazli

I'm Zharfan Mazli, a Developer Entrepreneur from Kerteh, Malaysia. I have worked with lots of programming languages like Qbasic, VB, Pascal, C# and recently PHP. Here I'll share codes and tutorials for others and myself.