Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add extra header information in codeigniter email

I would like to send some extra information on the emails which is sent from codeigniter library. Is there any way to configure or add this?

I want to categorize all the outgoing mail from my site. I need to include sendgrid category header for tracking.

like image 369
Arun SS Avatar asked Jan 30 '12 10:01

Arun SS


3 Answers

The CodeIgniter email class doesn't let you manually set headers. However you could change this by extending it and adding a new function that allows you to set the sendgrid headers.

See the "Extending Native Libraries" section of the CodeIgniter manual:
https://www.codeigniter.com/user_guide/general/creating_libraries.html
Here's what the code in your new email class might look like.

class MY_Email extends CI_Email {

    public function __construct(array $config = array())
    {
        parent::__construct($config);
     }

    public function set_header($header, $value){
        $this->_headers[$header] = $value;
    }
}

You'd then be able to set headers using your new email class like this:

$this->email->set_header($header, $value);

This page will explain what headers can be passed to SendGrid: http://sendgrid.com/docs/API%20Reference/SMTP%20API/

like image 150
tekniskt Avatar answered Oct 21 '22 03:10

tekniskt


Alright, I just want to improve the best answer here. Credit goes to @Tekniskt, and the only difference here is that the settings you might have in /application/config/email.php are ignored, which hurts, especially if you are using custom STMP settings.

Here's the full code of the class MY_Email.php I've improved from the answer above:

class MY_Email extends CI_Email {

public function __construct($config = array())
{
    if (count($config) > 0)
    {
        $this->initialize($config);
    }
    else
    {
        $this->_smtp_auth = ($this->smtp_user == '' AND $this->smtp_pass == '') ? FALSE : TRUE;
        $this->_safe_mode = ((boolean)@ini_get("safe_mode") === FALSE) ? FALSE : TRUE;
    }

    log_message('debug', "Email Class Initialized");
}

// this will allow us to add headers whenever we need them
public function set_header($header, $value){
    $this->_headers[$header] = $value;
  }
}

Hope it helps! :)

I did my test, and it seems now /config/email.php is included and settings are passed properly.

Cheers and thanks for the answer! :)

like image 29
d-wade Avatar answered Oct 21 '22 04:10

d-wade


Pass the $config parameter

class MY_Email extends CI_Email
{
  public function __construct(array $config = array())
  {
    parent::__construct($config);
  }

  public function set_header($header, $value)
  {
    $this->_headers[ $header ] = $value;
  }
}

Set custom header as

$this->email->set_header($header, $value);
like image 44
suvozit Avatar answered Oct 21 '22 04:10

suvozit