CodeIgniter 4 includes an Email class that sends mail through SMTP, mail() or sendmail.
Configure SMTP
Set these in .env (or in app/Config/Email.php):
email.fromEmail,email.fromNameemail.protocol = smtpemail.SMTPHost,email.SMTPUser,email.SMTPPassemail.SMTPPort = 587andemail.SMTPCrypto = tls(or 465 withssl)email.mailType = html
Use your provider's details (Gmail app password, Hostinger email, Zoho, SES…).
Send an email
$email = service('email');setTo(),setSubject(),setMessage()send()returnstrueorfalse
HTML emails
Build the body from a view: setMessage(view('emails/welcome', $data)).
Attachments, CC, BCC
attach($path), setCC(), setBCC(), setReplyTo().
Debugging
If send() returns false, echo $email->printDebugger(['headers']); shows the SMTP conversation and the error.
Sending in a loop for many users can be slow; send small batches or use a cron job.
Example
<?php
// .env
// email.fromEmail = no-reply@agyanadda.com
// email.fromName = AgyanAdda
// email.protocol = smtp
// email.SMTPHost = smtp.hostinger.com
// email.SMTPUser = no-reply@agyanadda.com
// email.SMTPPass = your-password
// email.SMTPPort = 465
// email.SMTPCrypto = ssl
// email.mailType = html
public function sendWelcome(array $user): bool
{
$email = service('email');
$email->setTo($user['email']);
$email->setSubject('Welcome to AgyanAdda!');
$email->setMessage(view('emails/welcome', ['name' => $user['name']]));
if (! $email->send()) {
log_message('error', $email->printDebugger(['headers']));
return false;
}
return true;
}
// app/Views/emails/welcome.php
// <h2>Hi <?= esc($name) ?>,</h2>
// <p>Thanks for joining. Start learning today!</p>
The user receives an HTML email "Hi Asha, Thanks for joining...". If sending fails, the SMTP error is written to writable/logs instead of breaking the page.