Black Friday Exclusive: Slash 31% Off Your WaaS Setup!

Creating Mailgun domains for your tenants

Most websites, at some point, will need to send E-mails. If your WPCS Product allows your customers to send E-mails to their customers, chances are that they will want to use their own domains for those E-mails. In this recipe, we’ll show you how to create Mailgun domains for your tenants and how to automate keeping Mailgun up-to-date.

Requirements #

  1. To utilize the Tenant Lifecycle Hooks, we’ll use the Code Snippets plugin. So make sure you install that as well.
  2. To automatically connect your tenant’s sites to Mailgun, we’ll use WP Mail SMTP by WPForms.
  3. You will need a Mailgun account to set up the WP Mail SMTP plugin.

Setting up WP Mail SMTP #

First, make sure that WP Mail SMTP is set up correctly and that you can send E-mails using your own domain. After installation, go to WP Mail SMTP’s settings screen and follow the instructions.

Creating new Mailgun domains for your tenants #

Whenever you create a tenant using the API, you can pass along a custom domain name. This will provision the tenant under that domain name, instead of a WPCS generated URL. First, let’s make sure that we create a Mailgun domain when a new tenant is created.

Make sure that the Code Snippets plugin is installed and ready to go. Then, add the following PHP snippet:

<?php

// Mailgun domains should be updated when the tenant is created, but also when its main domain changes
add_action('wpcs_tenant_created', 'create_mailgun_domain');
add_action('wpcs_tenant_main_domain_changed', 'create_mailgun_domain');

function create_mailgun_domain()
{
    // Get the currently configured domain, without the protocol
    $current_domain = str_replace(['http://', 'https://'], '', get_site_url());

    // Abort early if the current domain is a WPCS generated one
    if (strpos($current_domain, '.wpcs.io') !== false) {
        return;
    }

    // Let's use the API key that was used to configure the WP Mail SMTP plugin
    $mailgun_api_key = WPMailSMTP\Options::init()->get('mailgun', 'api_key');
    $auth_string = base64_encode("api:$mailgun_api_key");

    // Make sure you are using Mailgun's right region! Check out Mailgun's documentation to verify the API URL you should use.
    $mailgun_api_url = 'https://api.mailgun.net/v3/domains';

    // Make a POST request to Mailgun's API
    $mailgun_domain = "mailgun.$current_domain";
    $response = wp_remote_post($mailgun_api_url, [ 
        'body' => [
            'name' => $mailgun_domain,
        ],
        'headers' => [
            'Authorization' => "Basic $auth_string",
        ],
    ]);

    if (!is_wp_error( $response )) {
        // Store the response body for later use
        update_option('mailgun_domain_information', $response['body']);

        WPMailSMTP\Options::init()->set([
            'mailgun'     => [
                'domain' => $mailgun_domain,
            ],
        ], false, false);
    }
}
NOTE #

This snippet is based on WP Mail SMTP version 2.6.0. If the snippet malfunctions, check the plugin version you are using.

This snippet will run after the tenant is created. It reads the API key from the WP Mail SMTP plugin and uses it to make a call to Mailgun’s API. After this code runs, you’ll find your Mailgun account containing an extra domain, with the domain name you created your tenant under.

To complete the functionality, there’s one thing left to do: notify your customer of the required DNS configuration. Mailgun’s domains use DNS validation to make sure you own the domain name you want to use for emails, so it asks for proof by adding some DNS records.

These records can be found in the response from the wp_remote_post call in the snippet. You can find a response example in Mailgun’s documentation. You could use this data to send an e-mail to your customer (be sure to do this before changing WP Mail SMTP’s domain setting!), you could store the data in the site’s database and show it to your customer in the admin area, or any other way of communication you have set up for your WaaS.

Display the DNS requirements to your customer #

In order to let your tenant know about the DNS requirements, let’s add a simple dashboard widget in the admin area. Add a second PHP snippet with the following code:

<?php

add_action('wp_dashboard_setup', 'register_mailgun_domain_info_widget');
  
function register_mailgun_domain_info_widget() {
    global $wp_meta_boxes;

    // Add the widget, the second argument is the title of the widget
    wp_add_dashboard_widget('mailgun_domain_info_widget', 'Configure your E-mail', 'display_mailgun_domain_info');
}

function display_mailgun_domain_info() {
    // Get the information from the option that was created after the call to Mailgun's API
    $info = json_decode(get_option('mailgun_domain_information'));

    echo "<p>Welcome!</p>";
    echo "<p>In order to enable E-mails from this website, add the following records to your domain's DNS:</p>";

    // Loop over the record information and display the records one by one
    echo "<p>";
    foreach ($info->sending_dns_records as $record) {
        $record_type = $record->record_type;
        $record_name = $record->name;
        $record_value = $record->value;

        echo "<div>Type: <input readonly value=\"$record_type\" /></div>";
        echo "<div>Name: <input readonly value=\"$record_name\" /></div>";
        echo "<div>Value: <input readonly value=\"$record_value\" /></div>";
        echo "<br />";
    }
    echo "</p>";
}

This snippet will create a box in the dashboard with the information displayed from the option that was created in the previous snippet. Of course, this is a very basic way of displaying this information. Consider adding some styling to increase the readability of the information, supplying contact points for support, and maybe other information to make the dashboard widget even more useful.