Today, a user in SO asked how to make Codeigniter respect line breaks when sending emails.
Suppose it’s not quite trivial so, here’s what I suggest to do. Why not send the email has html?
First you must prepare the message (I’m assuming that you’re using POST):
$message = str_replace ("\r\n", "<br>", $this->input->post('message') );
or you can use the native php way to get $_POST
$message = str_replace ("\r\n", "<br>", $_POST['message'] );
What you’ve done, is to replace new lines with
Then you just need to load the lib and set it correctly trough config, for example:
$this->load->library('email'); $config['mailtype'] = 'html'; $this->email->initialize($config); $this->email->from('email@example.com', 'Your Name'); $this->email->to('firstname.lastname@example.org'); $this->email->subject('Email Test'); $this->email->message( $message ); $this->email->send();
That’s it! I hope this helps,
You can get more info on Codeigniter email docs Hopefully you’ll take the time to read it!
Just to add, you can simplify this process using nl2br and simply ->mailtype = ‘html’; Like so:
$message = nl2br($this->input->post('message')); // https://codeigniter.com/user_guide/libraries/input.html $this->load->library('email'); // use autoload.php to remove this line $this->email->mailtype = 'html';
Also, if you want to create a config to use all the time, you can actually create a config file and CI will use it automatically, thus you never need to use ->initialize. To do so, just follow these simple steps:
In the directory of application\config, create a file named email.php Then you can simply write in your configuration in that file like so:
`$config['mailtype'] = 'html';`
Viola, you’re done, it’s just that simple! Now just call your email class and use as usual with no need to configure things like mailtype. You can see full list of email config options under the title Email Preferences here. Don’t forget, you can use the application\config\autoload.php to load the email library automatically, thus removing this line $this->load->library(‘email’); from your code.