<?php
$page_title = 'Step 5 — Send a transactional email';
require 'header.php';
?>

<p>
    This is the core of the Transactional API:
    <span class="endpoint">POST /messages/send</span>. Everything else we've
    covered is just management around this one call. Pass it a recipient,
    subject, body and sender, and it delivers the email.
</p>

<div class="callout warn">
    <strong>Domain must be verified.</strong> The <code>from_email</code> has to
    be on a domain you've verified in Mandrill (Settings → Sending Domains) with
    SPF + DKIM records published. Unverified = instant rejection. See
    <a href="setup.php">Setup, step 5</a> if you haven't done this yet.
</div>

<h2>Try it</h2>

<form method="post">
    <label>To address</label>
    <input type="email" name="to_email" required value="<?= h($_POST['to_email'] ?? '') ?>" placeholder="recipient@example.com">

    <label>To name <small>(optional)</small></label>
    <input type="text" name="to_name" value="<?= h($_POST['to_name'] ?? '') ?>" placeholder="Recipient's name">

    <label>Subject</label>
    <input type="text" name="subject" required value="<?= h($_POST['subject'] ?? 'Hello from the Transactional API demo') ?>">

    <label>From email <small>(must be on a verified domain)</small></label>
    <input type="email" name="from_email" required value="<?= h($_POST['from_email'] ?? DEFAULT_FROM_EMAIL) ?>">

    <label>From name</label>
    <input type="text" name="from_name" value="<?= h($_POST['from_name'] ?? DEFAULT_FROM_NAME) ?>">

    <label>HTML body</label>
    <textarea name="html" rows="6"><?= h($_POST['html'] ?? "<h1>Hello!</h1>\n<p>This is a test from the Mailchimp Transactional API demo.</p>") ?></textarea>

    <label>Plain-text body <small>(fallback for clients that don't render HTML)</small></label>
    <textarea name="text" rows="4"><?= h($_POST['text'] ?? "Hello!\n\nThis is a test from the Mailchimp Transactional API demo.") ?></textarea>

    <button type="submit" name="run">Send email</button>
</form>

<?php
if (isset($_POST['run']) && is_configured() && !empty($_POST['to_email'])) {

    if (!recipient_allowed($_POST['to_email'])) {
        echo '<div class="callout warn"><strong>Recipient not on the test whitelist.</strong> '
           . 'Add <code>' . h($_POST['to_email']) . '</code> to <code>ALLOWED_TEST_RECIPIENTS</code> '
           . 'in <code>config.php</code>, or clear that list to allow any recipient.</div>';
        require 'footer.php';
        exit;
    }

    // --- Build the message object ----------------------------
    // The entire email is described by a single "message" array
    // passed inside the params. Mandrill accepts a LOT of optional
    // fields here (tracking, tags, metadata, attachments, merge vars) —
    // this demo uses the minimum required for a well-formed send.
    $message = [
        'from_email' => trim($_POST['from_email']),
        'from_name'  => trim($_POST['from_name']),
        'subject'    => trim($_POST['subject']),
        'html'       => $_POST['html'],
        'text'       => $_POST['text'],
        'to' => [
            [
                'email' => trim($_POST['to_email']),
                'name'  => trim($_POST['to_name']),
                'type'  => 'to',   // 'to', 'cc' or 'bcc'
            ],
        ],
        // Recommended defaults:
        'track_opens'  => true,
        'track_clicks' => true,
        'tags'         => ['demo-send'],  // shows up in your stats
    ];

    $result = mandrill_call('/messages/send', ['message' => $message]);
    // ---------------------------------------------------------

    if (!mandrill_is_error($result) && is_array($result['decoded'])) {
        foreach ($result['decoded'] as $recipient) {
            $status = $recipient['status'] ?? 'unknown';
            $class  = ($status === 'sent' || $status === 'queued') ? 'ok' : 'warn';
            echo '<div class="callout ' . $class . '">'
               . '<strong>' . h($recipient['email']) . ':</strong> '
               . h($status);
            if (isset($recipient['reject_reason']) && $recipient['reject_reason']) {
                echo ' — ' . h($recipient['reject_reason']);
            }
            echo '</div>';
        }
    }

    render_debug($result);
}
?>

<h2>The call</h2>

<pre><code>$result = mandrill_call('/messages/send', [
    'message' =&gt; [
        'from_email' =&gt; 'noreply@yourdomain.com',
        'from_name'  =&gt; 'Your Company',
        'subject'    =&gt; 'Welcome!',
        'html'       =&gt; '&lt;h1&gt;Hi&lt;/h1&gt;',
        'text'       =&gt; 'Hi',
        'to' =&gt; [
            ['email' =&gt; 'user@example.com', 'name' =&gt; 'User', 'type' =&gt; 'to'],
        ],
        'track_opens'  =&gt; true,
        'track_clicks' =&gt; true,
        'tags'         =&gt; ['welcome-email'],
    ],
]);</code></pre>

<h2>Response shape</h2>

<p>Unlike the other endpoints, <code>/messages/send</code> returns an <strong>array</strong> — one entry per recipient:</p>

<pre><code>[
    {
        "email":         "user@example.com",
        "status":        "sent",
        "reject_reason": null,
        "_id":           "abc123..."
    }
]</code></pre>

<p>Possible <code>status</code> values:</p>

<table>
<tr><th>Status</th><th>Meaning</th></tr>
<tr><td><code>sent</code></td><td>Accepted and delivered to the receiving mailserver.</td></tr>
<tr><td><code>queued</code></td><td>Accepted, will be delivered shortly.</td></tr>
<tr><td><code>scheduled</code></td><td>Held for a scheduled send time.</td></tr>
<tr><td><code>rejected</code></td><td>Mandrill refused to send — see <code>reject_reason</code>.</td></tr>
<tr><td><code>invalid</code></td><td>Malformed address or similar.</td></tr>
</table>

<p>Common <code>reject_reason</code> values you'll hit in testing:</p>

<ul>
    <li><code>unsigned</code> — the <code>from_email</code> domain isn't verified.</li>
    <li><code>hard-bounce</code> — recipient is on your denylist from a prior bounce.</li>
    <li><code>spam</code> — recipient previously complained. Allowlist the address (Step 3) to override.</li>
    <li><code>unsub</code> — recipient unsubscribed.</li>
</ul>

<h2>Useful optional fields</h2>

<p>You'll want these in production:</p>

<pre><code>'message' =&gt; [
    // ...required fields...

    // Group related sends so you can see aggregate stats by category
    'tags' =&gt; ['password-reset', 'customer-type:premium'],

    // Attach your own IDs for webhook correlation
    'metadata' =&gt; ['website_order_id' =&gt; 'ORD-12345'],

    // Merge fields — per-recipient variables
    'merge_vars' =&gt; [[
        'rcpt' =&gt; 'user@example.com',
        'vars' =&gt; [
            ['name' =&gt; 'FIRSTNAME', 'content' =&gt; 'Jane'],
        ],
    ]],

    // Reply-To header
    'headers' =&gt; ['Reply-To' =&gt; 'support@yourdomain.com'],

    // Don't let Mandrill auto-append your opens pixel / click redirects
    'track_opens'  =&gt; false,
    'track_clicks' =&gt; false,
]</code></pre>

<p><a href="06-templates-list.php">→ Next: templates</a></p>

<?php require 'footer.php'; ?>
