agyanadda@gmail.com

CodeIgniter 4 Sending Email

APIs and Advanced Topics 1 min read Updated Dec 3, 2026 Topic 25 of 30

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.fromName
  • email.protocol = smtp
  • email.SMTPHost, email.SMTPUser, email.SMTPPass
  • email.SMTPPort = 587 and email.SMTPCrypto = tls (or 465 with ssl)
  • email.mailType = html

Use your provider's details (Gmail app password, Hostinger email, Zoho, SES…).

Send an email

  1. $email = service('email');
  2. setTo(), setSubject(), setMessage()
  3. send() returns true or false

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

Example — Welcome email PHP
<?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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

How do you get the email service?

Exercise 2 True / False

printDebugger() helps find out why an email failed.

Exercise 3 Fill in the Blank

Use the ___() helper to build an HTML email body from a view file.

Frequently Asked Questions

Gmail needs an App Password (with 2-step verification on), not your normal password. Use smtp.gmail.com, port 587 with tls. For a business site, an email address on your own domain is more reliable.