In CodeIgniter 4, the email library allows users to send emails using SMTP (Simple Mail Transfer Protocol).
Here’s a step-by-step guide on how to send emails in CodeIgniter 4:
Step 1: Edit Email.php
First of all, visit app/config
directory and open email.php
file in any text editor.
Step 2: Configure Email SERVER
Now, add valid configuration in email.php
file, like the following:
public $SMTP = [
'protocol' => 'smtp',
'SMTPHost' => 'your-smtp-host', // e.g., smtp.example.com
'SMTPPort' => 465, // Port number for SMTP (e.g., 465 for SSL)
'SMTPUser' => 'your-smtp-username',
'SMTPPass' => 'your-smtp-password',
'SMTPCrypto' => 'ssl', // Encryption method (ssl, tls, or empty)
'mailType' => 'html', // Set email format: text or html
'charset' => 'UTF-8',
'validate' => true,
'CRLF' => "\r\n",
'newline' => "\r\n",
];
Note that:- If you are sending a mail using Gmail you have to allow non-secure apps to access Gmail you can do this by going to your Gmail settings here.
Once less secure apps are enabled; now you can use your Gmail for sending the emails.
Step 3: Send Email
Open your controller file and use the following code into it to send email using Gmail:
$email = \Config\Services::email();
$email->setTo('[email protected]');
$email->setFrom('[email protected]', 'Tutsmake.com');
$email->setSubject('Test Email');
$email->setMessage('This is a test email from CodeIgniter 4 with SMTP.');
if ($email->send()) {
echo 'Email sent successfully.';
} else {
echo 'Error sending email: ' . $email->printDebugger();
}
Using the 3 steps in this tutorial, you can send email from your Codeigniter 4 project with gmail smtp.
It is working for me.