← Back to all posts
2026-09-12 · MailAnvil Team

Cara Kirim Email Transaksional dari CodeIgniter 4 dengan MailAnvil API

CodeIgniter masih jadi framework PHP favorit banyak developer Indonesia — ringan, cepat, dokumentasi jelas. Tapi kalau urusan email transaksional, banyak yang masih pakai mail() bawaan PHP atau SMTP relay yang lambat.

MailAnvil punya REST API yang bisa dipanggil langsung dari CodeIgniter 4 tanpa library tambahan. Cukup file_get_contents atau Guzzle kalau sudah install. Tidak perlu setup SMTP, tidak perlu install SDK.

Kenapa REST API, Bukan SMTP?

SMTP bekerja lewat protokol text-based yang harus maintain koneksi persistent. REST API? Cukup POST JSON, dapat response, selesai.

Untuk CodeIgniter 4 yang di-deploy di shared hosting atau VPS murah, REST API lebih praktik:

Setup di CodeIgniter 4

1. Dapatkan API Key dari MailAnvil

Daftar di mailanvil.com, buat API key dari dashboard. Simpan di .env:

MAILANVIL_API_KEY=key_xxxxxxxxxxxxxxxx
MAILANVIL_ENDPOINT=https://api.mailanvil.com/v1

2. Buat Service Class

<?php
// app/Services/MailAnvilService.php

namespace App\Services;

class MailAnvilService
{
    private string $apiKey;
    private string $endpoint;

    public function __construct()
    {
        $this->apiKey = env('MAILANVIL_API_KEY');
        $this->endpoint = env('MAILANVIL_ENDPOINT', 'https://api.mailanvil.com/v1');
    }

    public function send(string $to, string $subject, string $html, array $options = []): array
    {
        $payload = [
            'from'    => $options['from'] ?? '[email protected]',
            'to'      => [$to],
            'subject' => $subject,
            'html'    => $html,
        ];

        if (!empty($options['reply_to'])) {
            $payload['reply_to'] = $options['reply_to'];
        }

        if (!empty($options['tags'])) {
            $payload['tags'] = $options['tags'];
        }

        $ch = curl_init($this->endpoint . '/send');
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($payload),
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->apiKey,
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return [
            'status' => $httpCode,
            'body'   => json_decode($response, true),
        ];
    }
}

3. Gunakan di Controller

<?php
// app/Controllers/OrderController.php

namespace App\Controllers;

use App\Services\MailAnvilService;

class OrderController extends BaseController
{
    public function store()
    {
        // Proses order di sini...

        $mail = new MailAnvilService();
        $result = $mail->send(
            '[email protected]',
            'Pesanan Anda Diterima',
            $this->view('emails/order-confirmation', ['order' => $order]),
            ['tags' => ['order', 'transactional']]
        );

        if ($result['status'] === 200) {
            return $this->response->setJSON(['message' => 'Order berhasil']);
        }

        return $this->response->setStatusCode(500)
            ->setJSON(['error' => 'Gagal mengirim email konfirmasi']);
    }
}

4. Template Email dengan View CodeIgniter

CodeIgniter 4 punya built-in template engine. Gunakan view() untuk render HTML email:

// app/Views/emails/order-confirmation.php

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: #ff801f; color: white; padding: 20px; text-align: center; }
        .content { padding: 20px; background: #f9f9f9; }
        .footer { padding: 15px; text-align: center; font-size: 12px; color: #999; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Pesanan Diterima</h1>
        </div>
        <div class="content">
            <p>Hai <?= esc($order['customer_name']) ?>,</p>
            <p>Pesanan #<?= esc($order['id']) ?> sudah kami terima.</p>
            <p>Total: Rp <?= number_format($order['total'], 0, ',', '.') ?></p>
            <p>Estimasi pengiriman: 2-3 hari kerja.</p>
        </div>
        <div class="footer">
            <p>MailAnvil — Email API Indonesia</p>
        </div>
    </div>
</body>
</html>

Handling Error & Retry

Jangan biarkan email gagal tanpa fallback. Tambahkan retry logic sederhana:

public function sendWithRetry(string $to, string $subject, string $html, int $maxRetries = 3): array
{
    $attempt = 0;
    while ($attempt < $maxRetries) {
        $result = $this->send($to, $subject, $html);

        if ($result['status'] === 200) {
            return $result;
        }

        $attempt++;
        if ($attempt < $maxRetries) {
            sleep(pow(2, $attempt)); // exponential backoff
        }
    }

    log_message('error', "MailAnvil failed after {$maxRetries} attempts: " . json_encode($result));
    return $result;
}

Harga untuk Developer Indonesia

MailAnvil mengenakan harga dalam Rupiah. Mulai dari Rp 25.000/bulan untuk 10.000 email. Pembayaran via QRIS, GoPay, atau transfer bank — tidak perlu kartu kredit.

Untuk aplikasi CodeIgniter yang baru mulai, biaya email transaksional tidak jadi beban besar.

Kesimpulan

CodeIgniter 4 + MailAnvil API = kombinasi ringan untuk email transaksional. Tidak perlu SMTP relay, tidak perlu library berat. Cukup curl, kirim JSON, dapat response.

Cocok untuk: konfirmasi order, OTP verifikasi, notifikasi status, email selamat datang.

Daftar gratis di mailanvil.com dan mulai kirim email dari CodeIgniter dalam 5 menit.