Envello
WooCommerce guide

Send email from WooCommerce

Route WooCommerce order, invoice and password emails through Envello's HTTP API with a 100-line must-use plugin: no SMTP, failures logged through wp_mail_failed.

Updated · 3 min read

WooCommerce doesn't send mail itself. Order confirmations, invoices, refund notices and password resets all go through WordPress's wp_mail(), which by default hands them to PHP's mail() on your web server. That's why store emails so often land in spam or never arrive: the server isn't authenticated to send for your domain.

Since WordPress 5.7, wp_mail() runs a pre_wp_mail filter before it touches PHPMailer. A filter that returns true or false replaces the whole send. So a small must-use plugin can send every wp_mail() call, WooCommerce's included, through Envello's HTTP API. There's no SMTP to configure, and Envello's SMTP relay isn't live yet anyway.

Before you start

Verify your sending domain in Envello and publish the DKIM and SPF records it shows. Use a subdomain such as mail.example-shop.eu so store mail has its own reputation. Then create a sending-access API key, which can send but can't manage domains or read logs.

Add the key and your sender address to wp-config.php. Keeping them out of the database means a leaked database dump doesn't leak the key.

// wp-config.php, above "That's all, stop editing!"
define('ENVELLO_API_KEY', 'env_live_...');
// An address on the domain you verified in Envello.
define('ENVELLO_FROM_EMAIL', '[email protected]');

The plugin

Save this as wp-content/mu-plugins/envello-mail.php. Must-use plugins load on every request and can't be switched off from the admin screen, which is what you want for mail. It converts wp_mail()'s arguments into one POST /emails request: recipients, CC and BCC from the headers, Reply-To, HTML or plain text depending on the content type, and attachments as base64.

<?php
/**
 * Plugin Name: Envello for wp_mail
 * Description: Sends every wp_mail() call, WooCommerce emails included, through the Envello API.
 */

if (!defined('ABSPATH')) {
    exit;
}

add_filter('pre_wp_mail', 'envello_send_wp_mail', 10, 2);

/**
 * Returning a non-null value from pre_wp_mail stops wp_mail() from using
 * PHPMailer. true means sent, false means failed.
 */
function envello_send_wp_mail($short_circuit, $atts) {
    if (null !== $short_circuit || !defined('ENVELLO_API_KEY') || !defined('ENVELLO_FROM_EMAIL')) {
        return $short_circuit;
    }

    $headers = envello_parse_headers($atts['headers']);
    // WooCommerce sets these filters around its own wp_mail() call, so they
    // carry the store's sender name and its HTML content type.
    $from_name = str_replace(['"', '<', '>'], '', apply_filters('wp_mail_from_name', get_bloginfo('name')));
    $content_type = $headers['content_type'] ?? apply_filters('wp_mail_content_type', 'text/plain');
    $body_field = false !== stripos($content_type, 'text/html') ? 'html' : 'text';

    $payload = [
        'from' => sprintf('%s <%s>', $from_name, ENVELLO_FROM_EMAIL),
        'to' => envello_address_list($atts['to']),
        'subject' => $atts['subject'],
        $body_field => $atts['message'],
        'tags' => [['name' => 'source', 'value' => 'wordpress']],
    ];
    if (!empty($headers['reply_to'])) {
        $payload['reply_to'] = $headers['reply_to'];
    }
    foreach (['cc', 'bcc'] as $field) {
        if (!empty($headers[$field])) {
            $payload[$field] = $headers[$field];
        }
    }
    $attachments = envello_attachments($atts['attachments']);
    if ($attachments) {
        $payload['attachments'] = $attachments;
    }

    $response = wp_remote_post('https://api.envello.dev/emails', [
        'timeout' => 15,
        'headers' => [
            'Authorization' => 'Bearer ' . ENVELLO_API_KEY,
            'Content-Type' => 'application/json',
        ],
        'body' => wp_json_encode($payload),
    ]);

    $status = wp_remote_retrieve_response_code($response);
    if (is_wp_error($response) || $status < 200 || $status >= 300) {
        $reason = is_wp_error($response) ? $response->get_error_message() : wp_remote_retrieve_body($response);
        do_action('wp_mail_failed', new WP_Error('envello_send_failed', $reason, $atts));
        return false;
    }

    do_action('wp_mail_succeeded', $atts);
    return true;
}

function envello_address_list($value) {
    $list = is_array($value) ? $value : explode(',', (string) $value);
    return array_values(array_filter(array_map('trim', $list)));
}

function envello_parse_headers($headers) {
    $lines = is_array($headers) ? $headers : explode("\n", str_replace("\r\n", "\n", (string) $headers));
    $parsed = ['cc' => [], 'bcc' => []];
    foreach ($lines as $line) {
        if (false === strpos($line, ':')) {
            continue;
        }
        [$name, $value] = array_map('trim', explode(':', $line, 2));
        switch (strtolower($name)) {
            case 'content-type':
                $parsed['content_type'] = $value;
                break;
            case 'reply-to':
                $parsed['reply_to'] = envello_address_list($value)[0] ?? null;
                break;
            case 'cc':
            case 'bcc':
                $parsed[strtolower($name)] = array_merge($parsed[strtolower($name)], envello_address_list($value));
                break;
        }
    }
    return $parsed;
}

function envello_attachments($attachments) {
    $files = is_array($attachments) ? $attachments : array_filter(explode("\n", (string) $attachments));
    $result = [];
    foreach ($files as $key => $path) {
        if (!is_readable($path)) {
            continue;
        }
        $filename = is_string($key) ? $key : basename($path);
        $attachment = ['filename' => $filename, 'content' => base64_encode(file_get_contents($path))];
        $type = wp_check_filetype($filename)['type'];
        if ($type) {
            $attachment['contentType'] = $type;
        }
        $result[] = $attachment;
    }
    return $result;
}

How WooCommerce's emails map to the API

WooCommerce sets three filters right before it calls wp_mail(): wp_mail_from, wp_mail_from_name and wp_mail_content_type. The plugin reads the sender name and content type through those filters, so the name from WooCommerce > Settings > Emails is used and order emails go out as html. The address always comes from ENVELLO_FROM_EMAIL, because Envello only sends from domains you've verified.

wp_mail() argumentEnvello field
$to (string or array)to (array of addresses, up to 50)
$subjectsubject
$messagehtml when the content type is text/html, otherwise text
Cc: and Bcc: headerscc, bcc
Reply-To: headerreply_to (first address)
$attachments (file paths, such as PDF invoices)attachments: [{ filename, content (base64), contentType }]
wp_mail_from_name filterDisplay name in from: "Shop <orders@...>"

Failures don't disappear

When the API returns an error, the plugin fires wp_mail_failed with the response body and returns false, exactly like a failed PHPMailer send. Anything already listening to that action, such as an error logger, keeps working. WooCommerce itself doesn't retry failed emails, so log them: add_action('wp_mail_failed', function ($error) { error_log($error->get_error_message()); }) is enough to start.

The status code tells you which side to fix. 400 means the payload didn't validate, for example a malformed address or more than 10 attachments. 401 means the key is wrong. 403 usually means the from address isn't on a verified domain. 422 means Envello refused the recipient: the address is on your suppression list, or its domain can't receive mail.

Test it

Use WooCommerce's own preview first (WooCommerce > Settings > Emails, then a template's preview link) to check the HTML. Then place a test order with a test-mode Envello key (env_test_...): the API accepts and logs the email without delivering it, so you can see the exact payload in the Envello dashboard before switching to the live key.

Then send one real order to an address you control and check the headers: Authentication-Results should show dkim=pass for your sending domain.

What this doesn't cover

If another mail plugin also hooks pre_wp_mail or replaces PHPMailer, only one of them should be active. The plugin skips the call when an earlier filter already handled it (non-null $short_circuit), but two mail plugins is a recipe for confusing bugs.

Bounces and complaints come back as Envello events. Envello suppresses hard-bounced and complaining addresses automatically, so a customer with a dead address won't be retried. If you want that status in WordPress, register a webhook endpoint and store the bounced flag on the customer.

Free tool

Check your domain's SPF, DKIM, and DMARC records

Paste in a domain and see what's missing, plus the exact DNS records to fix it. Free, no account needed.

Check your domain →