Email Generation and Delivery in CodeIgniter 4
In CodeIgniter 4, you can use the built-in Email library to send emails.
Configure Email Settings:
First, make sure you have configured your email settings in the app/config/Email.php
file. You can set up your email provider details, such as SMTP settings, there.
Here's an example:
$config = [ 'protocol' => 'smtp', 'SMTPHost' => 'your-smtp-host', 'SMTPUser' => 'your-smtp-username', 'SMTPPass' => 'your-smtp-password', 'SMTPPort' => 587, 'mailType' => 'html', 'charset' => 'utf-8', 'newline' => "\r\n", ];
Load the Email Library:
In your controller or wherever you want to send an email, load the Email library.
$email = \Config\Services::email();
Set Email Parameters:
Set the necessary parameters for your email, such as the sender's email address, recipient's email address, subject, message, etc. For example:
$email->setFrom('your-email@example.com', 'Your Name'); $email->setTo('recipient@example.com'); $email->setSubject('Subject of the email'); $email->setMessage('Message body of the email');
Attach Files :
If you need to attach files to your email, you can use the 'attach' method:
$email->attach('/path/to/file1.txt'); $email->attach('/path/to/file2.pdf');
Send Email:
Finally, use the send method to send the email:
$email->send();
Here's an example:
$email = \Config\Services::email(); $email->setFrom('your-email@example.com', 'Your Name'); $email->setTo('recipient@example.com'); $email->setSubject('Subject of the email'); $email->setMessage('Message body of the email'); // Attach files $email->attach('/path/to/file1.txt'); $email->attach('/path/to/file2.pdf'); $email->send();