How to Send Email in CodeIgniter via SMTP Server
Codeigniter comes with many built-in helpers and libraries for robust development. Of which its email library is a little gem that you can configure and send mails on fly. Here is a simple example to send email in codeigniter using smtp protocol. We'll see how to send mail with attachments through gmail, but you can use any third party smtpservers. Just get the smtp settings from the service provider and use it instead of gmail settings and you are done.
To send mail in codeigniter, you have to configure your email preferences like mail protocol, smtp authorization, html or plain text mail etc. These email preferences can be defined either globally or at the time of sending mails (like inside controllers).
Configure Email Preferences
Here we'll configure our email preferences globally in codeigniter. Create a file named'email.php' inside 'application/config' folder and add the below settings to it. These settings will be loaded and used automatically for sending emails.
<?php $config['protocol'] = 'smtp'; $config['smtp_host'] = 'ssl://smtp.gmail.com'; //change this $config['smtp_port'] = '465'; $config['smtp_user'] = 'user@gmail.com'; //change this $config['smtp_pass'] = 'password'; //change this $config['mailtype'] = 'html'; $config['charset'] = 'iso-8859-1'; $config['wordwrap'] = TRUE; $config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard ?>
The above is the smtp settings for gmail. The 'smtp_user' is your (gmail) email id and 'smtp_pass' is the email password.
Next we have to load the codeigniter email library and use its methods to send mail.
Code to Send Email in Codeigniter
Use this
sendmail()
function in a controller file to send email. You can load the 'email' library either inside the function or in the controller constructor.<?php //send mail function sendmail() { $this->load->library('email'); // load email library $this->email->from('user@gmail.com', 'sender name'); $this->email->to('test1@gmail.com'); $this->email->cc('test2@gmail.com'); $this->email->subject('Your Subject'); $this->email->message('Your Message'); $this->email->attach('/path/to/file1.png'); // attach file $this->email->attach('/path/to/file2.pdf'); if ($this->email->send()) echo "Mail Sent!"; else echo "There is error in sending mail!"; } ?>
All the above email methods like from(), to() are pretty self explanatory and I'll leave it to you. The method
$this->email->send()
will return a boolean value based upon if email is sent or not.
If you want to send mail in bulk, use comma separated email-id's in
$this->email->to()
method like this.
$this->email->to('test1@gmail.com, test2@gmail.com, test3@gmail.com');
This article on How to Send Email in CodeIgniter via SMTP Server is incredibly helpful! The step-by-step instructions make the process clear. If you're in need of reliable hosting services, check out Razor host for great performance and support!
ReplyDelete