Automating SureMails Setup in WordPress – Using MainWP

Tech Articles | August 19, 2025 | Automation, Blog, Coding, MainWP, Wordpress

As a follow on to this evenings over article about Automating SureMails Setup in WordPress I also wanted a way for more permanent sites and to be able to update those, after all using MainWP i can already install the plugin it would be really useful to be able to be able to setup the plugin too.

Well now you can using the following snippets, now I am not going to go into details about the MainWP snippet manager or how to use it beyond what’s important for this code because i’ve already covered it but there should be enough in this article to make it easy to understand and folow.

Setup your Connection

This snippet should be setup in the code snippets addon for MainWP and should be set to “return Info from child sites” NOT execute on child Sites.

Mainwp suremail snippet run

You will need to modify the setting block with your details but other than that its quick easy and doesn’t require you leaving your dashboard the snippet you need is below

<?php
/**
 * SureMails one-time setup via MainWP Code Snippets.
 * - Upserts a connection into `suremails_connections`
 * - Sets it as default
 * - Stores API key as Base64 (same as your schema)
 * - Idempotent: stable ID derived from (type + from_email + title)
 * - Does NOT depend on wp-config.php constants
 *
 * IMPORTANT: This snippet contains secrets while it’s saved in MainWP.
 * Run it once, verify, then DELETE the snippet from MainWP.
 */

/* ==== EDIT THESE PER RUN ==== */
$api_key_raw    = 'em_api_XXX';         // raw or base64 (both accepted)
$from_email     = 'example@email.com';
$from_name      = 'MainWP Test';
$type           = 'EMAILIT';                         // e.g. EMAILIT, SMTP, SES
$title          = 'Emailit Connection';
$priority       = 20;                                // lower number = higher priority
$log_emails     = 'yes';                             // optional global flags
$delete_logs    = '30_days';
$email_simulate = 'no';
/* ============================ */

if (!function_exists('is_email')) {
    // In case snippet runs outside full WP load (rare)
    function is_email($email){ return (bool) filter_var($email, FILTER_VALIDATE_EMAIL); }
}

$from_email = strtolower(trim($from_email));
if (!is_email($from_email)) {
    echo "Invalid from_email. Aborting.\n";
    return;
}

// Base64 helper
$is_base64 = static function ($s) {
    if (!is_string($s) || $s === '') return false;
    $decoded = base64_decode($s, true);
    return $decoded !== false && base64_encode($decoded) === $s;
};
$api_key_b64 = $is_base64($api_key_raw) ? $api_key_raw : base64_encode($api_key_raw);

// Load or bootstrap settings
$option_name = 'suremails_connections';
$settings    = get_option($option_name);
if (!is_array($settings)) {
    $settings = [
        'connections'             => [],
        'default_connection'      => null,
        'log_emails'              => $log_emails,
        'delete_email_logs_after' => $delete_logs,
        'email_simulation'        => $email_simulate,
    ];
}
if (!isset($settings['connections']) || !is_array($settings['connections'])) {
    $settings['connections'] = [];
}

// Stable ID from (type + from_email + title)
$id = md5(wp_json_encode([strtoupper($type), $from_email, $title]));

// Upsert connection
$new_conn = [
    'connection_title' => $title,
    'from_email'       => $from_email,
    'force_from_email' => true,
    'from_name'        => $from_name,
    'force_from_name'  => true,
    'priority'         => (int) $priority,
    'api_key'          => $api_key_b64,
    'id'               => $id,
    'type'             => strtoupper($type),
    'created_at'       => current_time('mysql'),
];

$settings['connections'][$id] = $new_conn;

// Set as default
$settings['default_connection'] = [
    'type'             => $new_conn['type'],
    'email'            => $new_conn['from_email'],
    'id'               => $new_conn['id'],
    'connection_title' => $new_conn['connection_title'],
];

// Persist and verify
update_option($option_name, $settings, false);
$verify = get_option($option_name);

$ok = is_array($verify)
   && isset($verify['connections'][$id])
   && isset($verify['default_connection']['id'])
   && $verify['default_connection']['id'] === $id;

if ($ok) {
    echo "SureMails connection created and set as default. ID: $id\n";
} else {
    echo "Failed to create or verify the SureMails connection.\n";
}
PHP

Now there will be times when you will likely ant to change the API key well the second snippet below allows you to do this

<?php
/**
 * SureMails — Rotate API Key (MainWP Code Snippet)
 *
 * Rotates the API key stored in the `suremails_connections` option.
 * Base64 is detected automatically; raw keys are encoded for storage.
 *
 * MODES:
 *  - 'default' : update ONLY the current default connection (recommended)
 *  - 'id'      : update ONLY the connection with a specific id (set $target_id)
 *  - 'all'     : update ALL connections
 *  - 'match'   : update connections that match (type + from_email + title)
 *
 * IMPORTANT: Run once, verify, then DELETE this snippet from MainWP.
 */

/* ====== CONFIG (edit these) ====== */
$new_key_raw = 'YOUR-NEW-API-KEY-HERE';  // raw or base64; both accepted

$mode = 'default';                       // 'default' | 'id' | 'all' | 'match'

$target_id = '';                         // required if $mode === 'id'

$match = [                                // used if $mode === 'match'
  'type'       => 'EMAILIT',             // case-insensitive
  'from_email' => 'example@techarticles.co.uk', // case-insensitive
  'title'      => 'Emailit Connection',  // exact match
];
/* ================================= */

/** Helpers */
$is_base64 = static function ($s) {
    if (!is_string($s) || $s === '') return false;
    $decoded = base64_decode($s, true);
    return $decoded !== false && base64_encode($decoded) === $s;
};
$redact = static function ($s) {
    $len = strlen($s);
    if ($len <= 8) return str_repeat('*', max(0, $len - 2)) . substr($s, -2);
    return substr($s, 0, 4) . str_repeat('*', $len - 8) . substr($s, -4);
};

if ($new_key_raw === '') {
    echo "No new key provided. Aborting.\n";
    return;
}
$api_key_b64 = $is_base64($new_key_raw) ? $new_key_raw : base64_encode($new_key_raw);

$option_name = 'suremails_connections';
$settings = get_option($option_name);

if (!is_array($settings) || empty($settings['connections']) || !is_array($settings['connections'])) {
    echo "No SureMails connections found on this site. Nothing to update.\n";
    return;
}

$updated = 0;
$targets = [];

/** Select targets based on mode */
switch ($mode) {
    case 'default':
        $def_id = $settings['default_connection']['id'] ?? null;
        if ($def_id && isset($settings['connections'][$def_id])) {
            $targets[] = $def_id;
        }
        break;

    case 'id':
        if ($target_id && isset($settings['connections'][$target_id])) {
            $targets[] = $target_id;
        }
        break;

    case 'all':
        $targets = array_keys($settings['connections']);
        break;

    case 'match':
        $want_type  = isset($match['type']) ? strtolower($match['type']) : '';
        $want_email = isset($match['from_email']) ? strtolower($match['from_email']) : '';
        $want_title = isset($match['title']) ? (string)$match['title'] : '';

        foreach ($settings['connections'] as $id => $conn) {
            $ok = true;
            if ($want_type  !== '' && strtolower($conn['type'] ?? '') !== $want_type) $ok = false;
            if ($want_email !== '' && strtolower($conn['from_email'] ?? '') !== $want_email) $ok = false;
            if ($want_title !== '' && ($conn['connection_title'] ?? '') !== $want_title) $ok = false;
            if ($ok) $targets[] = $id;
        }
        break;

    default:
        echo "Invalid mode: {$mode}. Use 'default', 'id', 'all', or 'match'.\n";
        return;
}

/** Update selected connections */
$targets = array_values(array_unique($targets));
if (empty($targets)) {
    echo "No matching connections to update for mode '{$mode}'.\n";
    return;
}

foreach ($targets as $id) {
    if (!isset($settings['connections'][$id])) continue;
    $settings['connections'][$id]['api_key'] = $api_key_b64;
    $updated++;
}

/** Persist */
update_option($option_name, $settings, false);

/** Report */
echo "Updated API key for {$updated} connection(s).\n";
if ($updated > 0) {
    echo "Targets:\n";
    foreach ($targets as $id) {
        $c = $settings['connections'][$id];
        printf("- id=%s | type=%s | title=%s | from=%s\n",
            $id, $c['type'] ?? '?', $c['connection_title'] ?? '?', $c['from_email'] ?? '?'
        );
    }
    echo "New key (redacted): " . $redact($new_key_raw) . "\n";
}
PHP

Now I don’t recommend keeping your API keys in your database other than on the child sites the same as Sure Mail does so i would keep these blank when keeping the snippets on the site and only updating them when you are sending and updating a site.

The Below video shows these snippets in action

Support the Author

buy me a coffee
Really Useful Plugin Logo
Wpvideobank temp
Appoligies for any spelling and grammer issue. As a dyslexic i need to rely on tools for this they like me are not perfect but I do try my best