Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Codeigniter 4 Send Email with Attachment Tutorial

Last Updated on August 1, 2024 by

In CodeIgniter 4 applications, the CodeIgniter\Email\Email library function attach() allows developers to create a feature for sending emails with attachments.

Let’s start sending an email with an attachment (file, image, etc.):

Step 1: Set Up Email Settings

Edit app/Config/Email.php file, and set up email details:

<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

class Email extends BaseConfig
{
    public $fromEmail = '[email protected]';
    public $fromName  = 'Your Name';
    public $recipients;

    public $protocol     = 'smtp';
    public $SMTPHost     = 'smtp.example.com';
    public $SMTPUser     = '[email protected]';
    public $SMTPPass     = 'your-email-password';
    public $SMTPPort     = 587;
    public $SMTPCrypto   = 'tls';

    public $mailType     = 'html';
    public $charset      = 'utf-8';
    public $wordWrap     = true;

    // Additional settings
    public $newline      = "\r\n";
    public $crlf         = "\r\n";
}

Step 2: Create a Controller

Go to app/Controllers directory, and create controller file named EmailController.php, and create some methods to send email with attachments:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\Email\Email;

class EmailController extends Controller
{
     public function index()
    {
        return view('send_email');
    }
}

Step 3: Create a Form in View

Go to app/Views directory, and create views named send_email.php, and send email form in it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Send Email with Attachment in CodeIgniter 4 - itcodstuff.com</title>
</head>
<body>
    <h1>Send Email with Attachment</h1>
    <form action="<?= base_url('email/send') ?>" method="post" enctype="multipart/form-data">
        <label for="email">Recipient Email:</label>
        <input type="email" name="email" required>
        <br>
        <label for="attachment">Attachment:</label>
        <input type="file" name="attachment" required>
        <br>
        <button type="submit">Send Email</button>
    </form>
</body>
</html>

Step 4: Add Send Email Method in Controller

Edit the EmailController.php file and add the following method in it to handle form submission and file upload:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\Email\Email;

class EmailController extends Controller
{


    public function sendEmail()
    {
        $email = \Config\Services::email();
        $email->setFrom('[email protected]', 'Your Name');
        $email->setTo($this->request->getPost('email'));
        $email->setSubject('Email Test with Attachment');
        $email->setMessage('This is a test email with an attachment.');

        // Handle file upload
        $file = $this->request->getFile('attachment');
        if ($file->isValid() && !$file->hasMoved()) {
            $filePath = WRITEPATH . 'uploads/' . $file->getName();
            $file->move(WRITEPATH . 'uploads');
            $email->attach($filePath);
        } else {
            return 'File upload error.';
        }

        if ($email->send()) {
            return 'Email successfully sent.';
        } else {
            $data = $email->printDebugger(['headers']);
            return $data;
        }
    }
}

Step 5: Define Routes

Edit app/Config/Routes.php file, and define routes in it:

$routes->get('email', 'EmailController::index');
$routes->post('email/send', 'EmailController::sendEmail');

Step 6: Test the Application

Type the url http://localhost:8080/email in your web browser.

Leave a Comment