CodeIgniter 4 includes an email library that sends plain text and HTML messages through mail, sendmail or SMTP. For anything beyond a test, SMTP through a relay is the right choice: it authenticates the sender, encrypts the connection and gives you a useful error when something fails. This guide shows the configuration in app/Config/Email.php and in .env, a working example that sends HTML with an attachment, how to read the debugger output, the errors you are most likely to meet (especially on shared hosting, where PHP and outbound ports are restricted) and what to do so that your messages reach the inbox. The settings use placeholders. Take the real host, user name and password from your SMTP provider's dashboard and never commit them to version control.
Configure SMTP in Email.php
Open app/Config/Email.php. These properties control SMTP. Set only what you need and leave the rest at defaults.
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '[email protected]';
public string $fromName = 'Example App';
public string $protocol = 'smtp';
public string $SMTPHost = 'smtp.example.com';
public string $SMTPUser = '';
public string $SMTPPass = '';
public int $SMTPPort = 587;
public int $SMTPTimeout = 30;
public bool $SMTPKeepAlive = false;
public string $SMTPCrypto = 'tls'; // 'tls' = STARTTLS, 'ssl' = implicit TLS
public string $mailType = 'html';
public string $charset = 'UTF-8';
public string $newline = "\r\n";
public string $CRLF = "\r\n";
}The two settings that cause the most confusion are SMTPCrypto and SMTPPort. They must match. Use tls with port 587 for STARTTLS, or ssl with port 465 for implicit TLS. A mismatch leads to timeouts or a handshake error. Keep newline and CRLF as "\r\n", because SMTP requires it, and a change of these values is a known cause of broken messages. If you are unsure which port to choose, read which SMTP port to use.
Keep secrets in .env
CodeIgniter 4 lets you override configuration properties from the .env file using the class name as a prefix. This keeps credentials out of your code, and it lets each environment use its own values. Leave the credential properties empty in Email.php and set them in .env instead:
email.protocol = smtp
email.SMTPHost = smtp.example.com
email.SMTPPort = 587
email.SMTPCrypto = tls
email.SMTPUser = your-smtp-user
email.SMTPPass = "your-smtp-password"
email.fromEmail = [email protected]
email.fromName = "Example App"Quote any value that contains spaces, a hash sign or other special characters. An unquoted # begins a comment and truncates the password, which results in an authentication error. Make sure .env is outside the web-accessible folder or blocked by the server, and that your production environment really loads it, since a missing file means empty credentials. If a login fails with a 535 reply, see SMTP error 535.
Send an HTML email with an attachment
Get the email service, set the addresses, the subject and the message, optionally attach a file, and call send(). Check the return value, because the library returns false on failure and does not throw by default.
<?php
namespace App\Controllers;
class Mailer extends BaseController
{
public function welcome()
{
$email = \Config\Services::email();
$email->setFrom('[email protected]', 'Example App');
$email->setTo('[email protected]');
$email->setReplyTo('[email protected]', 'Example Support');
$email->setSubject('Welcome to Example');
$email->setMessage(view('emails/welcome', ['name' => 'Alex']));
$email->setAltMessage('Thanks for signing up.');
$email->attach(WRITEPATH . 'uploads/guide.pdf');
if (! $email->send()) {
log_message('error', $email->printDebugger(['headers']));
return $this->response->setStatusCode(500)->setBody('The message could not be sent.');
}
return $this->response->setBody('Sent');
}
}setAltMessage() adds the plain-text part, which improves inbox placement and helps readers whose clients do not show HTML. A view file keeps the HTML out of your controller. Use inline styles and simple tables in email templates, because many mail clients ignore external CSS and modern layout features. Our HTML email template guide shows what renders reliably.
Use different settings for one message
If you need a different account for a particular message, create the service with a configuration array, or call initialize(). The array overrides the values from Email.php for that instance only.
$email = \Config\Services::email([
'SMTPHost' => 'smtp.example.com',
'SMTPUser' => $user,
'SMTPPass' => $pass,
'SMTPPort' => 587,
'SMTPCrypto' => 'tls',
'protocol' => 'smtp',
]);Read the debugger output
When send() returns false, call $email->printDebugger(). It returns a block of text that lists the server replies and, with the argument ['headers'], the headers of the message. Do not print it to users, since it can reveal internal details. Write it to the log as shown above, or show it only in development. The lines that matter are the server replies that begin with a three-digit code. The first non-2xx and non-3xx code is where the exchange broke. Our guide to SMTP reply codes explains what they mean.
Common errors and fixes
| Message | Usual cause | Fix |
|---|---|---|
| Unable to send email using SMTP. Your server might not be configured to send mail using this method. | The connection failed: wrong host or port, blocked outbound port, or crypto mismatch | Check host and port, match SMTPCrypto to the port and test the connection from the same server |
| Failed to authenticate password. Error: 535 ... | Wrong credentials, or truncated or unquoted values in .env | Re-copy the credentials, quote the password and confirm that .env is loaded |
| Unable to send using SMTP. fsockopen error / connection refused or timed out | Outbound SMTP is blocked by the host or a firewall | Ask the host to allow the port, or try a supported alternative port |
| STARTTLS failed / wrong version number | ssl used with port 587, or tls used with port 465 | Use tls with 587 and ssl with 465 |
| Messages look broken or have extra line breaks | newline or CRLF changed from "\r\n" | Restore both to "\r\n" |
| Sender address rejected / not allowed | The From address is not on a verified domain | Send from an address on a domain you have authenticated |
| Works locally, fails on the server | Different PHP version, missing OpenSSL extension, or outbound blocking | Check phpinfo() for OpenSSL and test the port from the server |
Shared hosting: what to check
Many CodeIgniter sites run on shared hosting. It has quirks that explain most "works on my laptop" failures. First, outbound connections on ports 25 and sometimes 465 or 587 can be blocked, so ask your host which ports are open. Second, the PHP version is often fixed, and CodeIgniter 4 releases have minimum PHP requirements, so a project may be held at an older framework version. Third, the OpenSSL extension must be enabled for TLS. Fourth, the server clock must be correct, because TLS certificate checks fail when the time is far off. Fifth, check that your writable folder is writable so that logs can be written, otherwise you will not see the error you need. If the host's own mail server rewrites or limits outgoing mail, use an external relay instead and point SMTPHost at it.
Send many messages without waiting
Sending inside a web request makes the page wait for the SMTP conversation. For a contact form, one message is fine. For anything that sends several messages, or that must be reliable, move mail to a background job. CodeIgniter 4 includes the spark command system, so a simple pattern is to save messages to a database table with a status, and run a command from cron that sends pending messages in small batches, marks them as sent or failed and records the error text. Set SMTPKeepAlive to true inside such a command to reuse one connection for the batch, and call $email->clear() between messages, so that recipients and attachments do not carry over. Handle temporary errors with a delay and stop retrying permanent ones, using the pattern in rate limits, retries and backoff.
Protect your forms from abuse
Contact and sign-up forms that send email are a favourite target for spammers. Validate the input with the validation library, never put user-supplied values into headers without checking them, limit how often one visitor can submit, and use a CAPTCHA or token check. An open form can burn the reputation of your sending domain within hours. Our guide to email validation before sending lists useful checks.
Deliverability for CodeIgniter mail
The library produces a valid message, but inbox placement depends on your domain. Authenticate the domain in the From address with SPF, DKIM and DMARC, using the records your provider gives you, and check them with the SPF, DKIM and DMARC checker. Send from a real, monitored address, include the plain-text alternative, and keep transactional mail separate from marketing mail. Read the complaint and bounce data your provider exposes, and remove invalid addresses so that you do not keep sending to them. The guides on authenticating your sending domain and the spam troubleshooting checklist are the best next steps.
Connect CodeIgniter to a managed relay Use the SMTP host and credentials from your dashboard and send a first message in minutes.
References and further reading
Frequently asked questions
Which SMTPCrypto value should I use in CodeIgniter 4?
Use tls with port 587 for STARTTLS, or ssl with port 465 for implicit TLS. The crypto setting and the port must match.
How do I see why the CodeIgniter email did not send?
Check the return value of send(), then write $email->printDebugger(['headers']) to the log. The first non-successful server reply shows where the exchange failed.
Can I store SMTP credentials in .env?
Yes. Use email.SMTPUser, email.SMTPPass and the other email.* keys, and quote values that contain special characters such as a hash sign.
Why does CodeIgniter say unable to send email using SMTP?
The connection or login failed. Check the host and port, match the crypto setting to the port, confirm credentials and ask your host whether outbound SMTP ports are open.
Should I send email directly in the controller?
For one message, it works. For several messages or reliability, queue the messages in a table and send them from a spark command run by cron.