Sending Email
CodeIgniter's email service supports SMTP and local mail transports. Keep mail credentials in .env and send through a service or library so controllers stay small.
Configure SMTP
email.protocol = smtp
email.SMTPHost = smtp.example.com
email.SMTPUser = mailer@example.com
email.SMTPPass = secret
email.SMTPPort = 587
email.SMTPCrypto = tls
email.fromEmail = no-reply@example.com
email.fromName = 'Example App'
Send a message
$email = \Config\Services::email();
$email->setFrom('no-reply@example.com', 'Example App');
$email->setTo('student@example.com');
$email->setSubject('Your enrollment is confirmed');
$email->setMessage('<p>Thanks for joining. Your course is ready.</p>');
if (! $email->send()) {
log_message('error', 'Email failed: {debug}', ['debug' => $email->printDebugger(['headers'])]);
}
setMessage() accepts HTML when the message type is HTML. Set a plain-text alternative when recipients may use clients that block HTML.
Attachments
$email->attach('/path/to/invoice.pdf');
$email->attach('/path/to/receipt.png', 'inline');
Practical advice
- Use a dedicated mail provider and authenticate with SMTP rather than sending directly from the web server.
- Never put credentials in code or version control.
- Send from a monitored address and set a reply-to address.
- Handle failures and log the debugger output, not the password.
- For bulk or slow mail, queue the work in a background job instead of delaying the HTTP response.
- Test with a real inbox and check spam scores before launch.
Back to course overview · Previous: File Uploading · Next: Form Validation