Tutorials

Send a Delayed Email After User Registration in WordPress

10 min read

WordPress can send a welcome email the moment someone signs up. Sending one later is harder: tips an hour after registration, a nudge on day 3, a check-in on day 7. This tutorial shows how to send a delayed email after user registration in WordPress with one small plugin file, the user_register hook, a REST endpoint and Delay, which calls your site when each email is due.

The result: emails go out on time even when nobody is visiting your site, a user never gets the same email twice, deleted users are skipped, and an email that fails because your site was down is retried.

How it works

  1. A user registers, and WordPress fires the user_register hook.
  2. Your plugin asks Delay to call an endpoint on your site in 1 hour, in 3 days and in 7 days: one job per email.
  3. When a job is due, Delay sends a signed POST request to that endpoint.
  4. The endpoint checks the signature, loads the user, makes sure the email hasn't gone out yet and still makes sense, and sends it with wp_mail().

The important idea is in step 4. You don't schedule the email itself, you schedule a call to your own code, and your code decides at send time. If the user deleted their account or already did what the email asks, the endpoint skips it.

Why not WP-Cron?

WordPress has its own scheduler, wp_schedule_single_event(), but WP-Cron only runs when someone loads a page. On a quiet site an email due at 9:00 waits for the next visitor, and a page cache that serves pages without loading WordPress delays it further. You can fix that by setting DISABLE_WP_CRON and running WP-Cron from a real server cron, if your host lets you.

Delay calls your site at the scheduled time whether anyone visits or not, retries when the site doesn't answer, and shows every run with your site's response, so you can see what happened to each email.

What you need

  • A WordPress site that's reachable from the internet. Delay can't call localhost, so test on a staging site or through a tunnel.
  • A Delay account. The free plan includes 1,000 requests a month. Each email is one request (plus one per retry), so three emails per signup cover about 330 signups a month.
  • Access to your site's files (SFTP or your host's file manager) to edit wp-config.php and add a plugin file.

Step 1: Get a Delay token and signing secret

  1. Sign up at delay.run and open the dashboard.
  2. Go to Settings > API tokens. Under Team tokens, name a token WordPress, choose Full access and click Create token. Copy it now: it's shown only once.
  3. Go to Settings > Webhook signing and click Generate secret. Copy the secret. Delay signs its requests only once a secret exists.
  4. Add both to wp-config.php, above the line that says "That's all, stop editing!":
define( 'DELAY_TOKEN', 'dly_your_token' );
define( 'DELAY_SIGNING_SECRET', 'your_signing_secret' );

Keeping them in wp-config.php keeps them out of the database and out of your theme.

Step 2: Create the plugin file and list your emails

Create a file named delayed-emails.php in wp-content/mu-plugins/ (create the mu-plugins folder if it doesn't exist). WordPress loads every file in that folder automatically, so there's nothing to activate, and nobody can switch it off by accident on the Plugins screen.

Every code block in this tutorial goes into this one file, in order. Rename the acme_ prefix to something unique to your site.

<?php
/**
 * Plugin Name: Delayed emails after registration
 * Description: Sends follow-up emails after a user registers, scheduled with Delay.
 */

defined( 'ABSPATH' ) || exit;

/**
 * The emails to send after registration. delay is in seconds, up to 365 days.
 * %s in the message is replaced with the user's display name.
 */
function acme_delayed_emails() {
    return array(
        'welcome-tips' => array(
            'delay'   => HOUR_IN_SECONDS,
            'subject' => 'Three tips to get started',
            'message' => "Hi %s,\n\nThanks for joining. Here are three things most people do first: ...",
        ),
        'day-3'        => array(
            'delay'   => 3 * DAY_IN_SECONDS,
            'subject' => 'Need a hand?',
            'message' => "Hi %s,\n\nIt's been a few days. If anything is unclear, just reply to this email.",
        ),
        'day-7'        => array(
            'delay'   => 7 * DAY_IN_SECONDS,
            'subject' => 'How is it going?',
            'message' => "Hi %s,\n\nYou've been with us for a week. What would make the site more useful to you?",
        ),
    );
}

To add an email later, add an entry here. It applies to users who register from then on.

Step 3: Schedule the emails when someone registers

This function asks Delay to call your endpoint after a delay, and the hook below calls it once per email when a user registers:

/**
 * Asks Delay to call our endpoint after $delay seconds. Returns the job ID, or null.
 */
function acme_schedule_email( $user_id, $key, $delay ) {
    $response = wp_remote_post( 'https://app.delay.run/api/v1/jobs', array(
        'timeout' => 5,
        'headers' => array(
            'Authorization'   => 'Bearer ' . DELAY_TOKEN,
            'Content-Type'    => 'application/json',
            'Idempotency-Key' => "user-{$user_id}-{$key}",
        ),
        'body'    => wp_json_encode( array(
            'queue'   => 'wordpress-emails',
            'url'     => rest_url( 'acme/v1/delayed-email' ),
            'payload' => array( 'user_id' => $user_id, 'email' => $key ),
            'delay'   => $delay,
        ) ),
    ) );

    if ( is_wp_error( $response ) || 201 !== wp_remote_retrieve_response_code( $response ) ) {
        error_log( "Delay: could not schedule {$key} for user {$user_id}" );
        return null;
    }

    $job = json_decode( wp_remote_retrieve_body( $response ), true );

    return isset( $job['id'] ) ? $job['id'] : null;
}

add_action( 'user_register', function ( $user_id ) {
    $job_ids = array();

    foreach ( acme_delayed_emails() as $key => $email ) {
        $job_id = acme_schedule_email( $user_id, $key, $email['delay'] );

        if ( $job_id ) {
            $job_ids[ $key ] = $job_id;
        }
    }

    update_user_meta( $user_id, 'acme_delay_jobs', $job_ids );
} );

What each part of the request does:

  • url is the endpoint you'll add in step 4. rest_url() builds the right address for your site, including on sites with plain permalinks.
  • payload is what Delay sends back when the job runs: which user, and which email.
  • delay is in seconds. Delay accepts up to 365 days, so a 30-day or 90-day email works the same way.
  • queue groups these jobs in the Delay dashboard. Delay creates the queue on first use with its defaults: a 30-second timeout and 3 retries.
  • Idempotency-Key makes the call safe to repeat. If the same registration triggers it twice, Delay schedules one job, not two.

The job IDs are saved in user meta so that step 6 can cancel them. user_register fires for every new account: people who sign up themselves, users you add under Users > Add New, and customer accounts that WooCommerce creates at checkout.

Step 4: Add the endpoint Delay calls

Delay signs each request with your secret: the X-Delay-Signature header holds an HMAC-SHA256 of the timestamp, a period and the raw body. Checking it means nobody else can make your site send these emails.

add_action( 'rest_api_init', function () {
    register_rest_route( 'acme/v1', '/delayed-email', array(
        'methods'             => 'POST',
        'callback'            => 'acme_send_delayed_email',
        'permission_callback' => 'acme_verify_delay_signature',
    ) );
} );

/**
 * Accepts the request only if Delay signed it in the last 5 minutes.
 */
function acme_verify_delay_signature( WP_REST_Request $request ) {
    $signature = (string) $request->get_header( 'X-Delay-Signature' );
    $timestamp = (string) $request->get_header( 'X-Delay-Timestamp' );

    if ( '' === $signature || ! ctype_digit( $timestamp ) || abs( time() - (int) $timestamp ) > 300 ) {
        return new WP_Error( 'invalid_signature', 'Invalid signature', array( 'status' => 401 ) );
    }

    $expected = hash_hmac( 'sha256', $timestamp . '.' . $request->get_body(), DELAY_SIGNING_SECRET );

    if ( ! hash_equals( $expected, $signature ) ) {
        return new WP_Error( 'invalid_signature', 'Invalid signature', array( 'status' => 401 ) );
    }

    return true;
}

WordPress runs permission_callback before the endpoint itself. get_body() returns the body exactly as Delay sent it, which is what the signature covers. If the secret is wrong, the run fails with a 401 in Delay's dashboard, so you notice straight away.

Step 5: Send the email, or skip it

This is the code that runs when an email is due. It loads the user, skips the email if it no longer applies, and sends it with wp_mail():

function acme_send_delayed_email( WP_REST_Request $request ) {
    $user_id = (int) $request->get_param( 'user_id' );
    $key     = (string) $request->get_param( 'email' );
    $emails  = acme_delayed_emails();
    $user    = get_userdata( $user_id );

    if ( ! $user || ! isset( $emails[ $key ] ) ) {
        return array( 'skipped' => 'unknown user or email' );
    }

    if ( get_user_meta( $user_id, "acme_sent_{$key}", true ) ) {
        return array( 'skipped' => 'already sent' );
    }

    if ( ! acme_should_send( $user, $key ) ) {
        return array( 'skipped' => 'no longer relevant' );
    }

    $email = $emails[ $key ];
    $sent  = wp_mail( $user->user_email, $email['subject'], sprintf( $email['message'], $user->display_name ) );

    if ( ! $sent ) {
        return new WP_Error( 'mail_failed', 'wp_mail() could not send the email', array( 'status' => 500 ) );
    }

    update_user_meta( $user_id, "acme_sent_{$key}", time() );

    return array( 'sent' => $key );
}

/**
 * Your rules for whether an email still makes sense. Return false to skip it.
 */
function acme_should_send( WP_User $user, $key ) {
    if ( get_user_meta( $user->ID, 'acme_unsubscribed', true ) ) {
        return false;
    }

    // Example for WooCommerce: skip the day 3 nudge if they've already ordered.
    if ( 'day-3' === $key && function_exists( 'wc_get_customer_order_count' ) ) {
        return 0 === wc_get_customer_order_count( $user->ID );
    }

    return true;
}

The response tells Delay what to do next:

  • A skipped email returns 200. Delay records the run as successful and doesn't retry, which is what you want.
  • A failed send returns 500. Delay retries it, by default after 1 minute, 30 minutes and 3 hours. If every attempt fails, the job waits in the dead letter queue, where you can replay it from the dashboard.
  • The acme_sent_ marker stops a second send. If your site sent the email but answered too slowly, Delay retries, and the marker turns that retry into a skip.

Step 6: Cancel pending emails when a user is deleted

The endpoint already skips deleted users, but cancelling their jobs saves requests from your monthly allowance:

add_action( 'delete_user', function ( $user_id ) {
    $job_ids = get_user_meta( $user_id, 'acme_delay_jobs', true );

    foreach ( is_array( $job_ids ) ? $job_ids : array() as $job_id ) {
        wp_remote_post( "https://app.delay.run/api/v1/jobs/{$job_id}/cancel", array(
            'timeout' => 5,
            'headers' => array( 'Authorization' => 'Bearer ' . DELAY_TOKEN ),
        ) );
    }
} );

A job that has already run can't be cancelled. Delay answers that call with a 409, which is safe to ignore here.

Step 7: Test it

  1. Change the welcome-tips delay to 60 for now.
  2. Register a test user, or add one under Users > Add New.
  3. Open Jobs in the Delay dashboard. You should see three jobs in the wordpress-emails queue, due in 1 minute, 3 days and 7 days.
  4. After a minute the first job runs. Open it to see the request Delay sent and your site's answer, {"sent":"welcome-tips"}.
  5. Check the test user's inbox, then set the delay back to HOUR_IN_SECONDS.

If the run succeeded but the email never arrived, the problem is mail delivery, not scheduling. Many hosts don't deliver mail sent from PHP reliably. An SMTP plugin such as WP Mail SMTP sends wp_mail() through a real email provider.

If a run fails, the dashboard shows your site's response. The usual causes:

The run shows Likely cause Fix
401 Invalid signature The secret in wp-config.php doesn't match Delay's Copy it again from Settings > Webhook signing
404 The plugin file isn't loaded Put it directly in mu-plugins, not in a subfolder
403, or an HTML page A security plugin or firewall blocks the request Allow POST requests to the endpoint's path
500 mail_failed wp_mail() failed Set up SMTP for your site

If no jobs show up in Delay at all, look for "Delay: could not schedule" in your PHP error log. The token is usually wrong or read-only.

Send at a set time of day

Exactly 3 days after a registration at 2 a.m. is 2 a.m. To send at 9:00 in your site's time zone instead, replace delay in the request body with run_at:

$send_at = ( new DateTimeImmutable( 'today 09:00', wp_timezone() ) )->modify( '+3 days' );

// in the body of the request in acme_schedule_email(), instead of 'delay':
'run_at' => $send_at->format( DATE_ATOM ),

wp_timezone() is the time zone set under Settings > General. WordPress doesn't store a time zone for each user, so this uses the site's.

Other ways to do it

  • WP-Cron with a real cron job. Schedule with wp_schedule_single_event() on user_register, add define( 'DISABLE_WP_CRON', true ); to wp-config.php, and have your server run wp cron event run --due-now every few minutes. This works well if you control the server.
  • An email marketing plugin. MailPoet can send a welcome email some hours, days or weeks after a new WordPress user is added, and FluentCRM has a New User Sign Up trigger with a wait step. That suits newsletter-style emails you'd rather edit in the dashboard.

FAQ

Can I send an email 30 days after registration?

Yes. A Delay job can be scheduled up to 365 days ahead, so add an entry with 'delay' => 30 * DAY_IN_SECONDS.

What happens if my site is down when an email is due?

The attempt fails and Delay retries it after 1 minute, 30 minutes and 3 hours. If the site is still down after that, the job waits in the dead letter queue until you replay it from the dashboard.

Can a user get the same email twice?

No. The Idempotency-Key stops a repeated registration call from scheduling a second job, and the acme_sent_ user meta stops a retry from sending an email that already went out.

Does this work for WooCommerce customers?

Yes. WooCommerce creates customer accounts as WordPress users, so user_register fires for them too. Use acme_should_send() to tailor the emails, as in the order count example above.

Does it slow down registration?

It adds one HTTP call per email to the registration request. Each call has a 5-second timeout, and a failed call is written to the error log instead of stopping the registration.

Schedule your first cron job

Free for 1,000 requests a month. No credit card.

Read the docs