How to send email using mail_lib library in codeigniter
In CodeIgniter, you can use the email
library to send emails. Here's an example of how to use it:
Step 1: Load the Email Library
In your controller, load the email
library:
$this->load->library('email');
Step 2: Set the Email Configuration
Set the email configuration in the email
library:
$this->email->from('[email protected]', 'Your Name');
$this->email->to('[email protected]');
$this->email->subject('Test Email');
$this->email->message('This is a test email');
Step 3: Send the Email
Send the email using the send()
method:
$this->email->send();
Full Example
Here's the full example:
<?php
class MyController extends CI_Controller {
public function send_email()
{
$this->load->library('email');
$this->email->from('[email protected]', 'Your Name');
$this->email->to('[email protected]');
$this->email->subject('Test Email');
$this->email->message('This is a test email');
$this->email->send();
echo 'Email sent!';
}
}
Configuring the Email Library
You can configure the email library by modifying the email.php
file in the application/config
directory. Here are some common settings:
smtp_host
: The SMTP host (e.g.smtp.gmail.com
)smtp_user
: The SMTP username (e.g.[email protected]
)smtp_pass
: The SMTP password (e.g.your_password
)smtp_port
: The SMTP port (e.g.587
)mailtype
: The email type (e.g.text
orhtml
)charset
: The character set (e.g.utf-8
)
For example:
<?php
$config['email'] = array(
'smtp_host' => 'smtp.gmail.com',
'smtp_user' => '[email protected]',
'smtp_pass' => 'your_password',
'smtp_port' => 587,
'mailtype' => 'text',
'charset' => 'utf-8'
);
?>
Note that you may need to configure your email provider's settings to allow less secure apps to access your account.