Setting up automated email communication within WordPress themes
Themes sometimes notify administrators when a custom form shortcode submits, or send learners a download link after signup.
WordPress provides wp_mail() as a wrapper around PHP mail; on production blogs you should route mail through SMTP for deliverability.
Basic wp_mail example
Always sanitize email addresses with sanitize_email and validate before sending.
Set HTML content type only when you send properly escaped HTML bodies.
add_action('init', function () {
if (!isset($_POST['gt_contact_nonce'])) {
return;
}
if (!wp_verify_nonce($_POST['gt_contact_nonce'], 'gt_contact')) {
return;
}
$to = get_option('admin_email');
$subject = 'New tutorial feedback';
$body = sanitize_textarea_field($_POST['message'] ?? '');
wp_mail($to, $subject, $body);
});Below is how the output typically looks in a browser, terminal, or API client:
Example ran successfully.
Pair forms with nonces (shown above) to mitigate CSRF inside WordPress, similar to PHP sessions in our backend module.
SMTP configuration
Use reputable SMTP plugins or define constants in wp-config.php for transactional providers.
Align SPF, DKIM, and DMARC DNS records with your sending domain so Gmail and Outlook accept messages.
Automation without spamming users
- Send only transactional mail users requested (welcome, password reset).
- Provide unsubscribe for marketing lists—use a dedicated newsletter tool.
- Log failures with
wp_mail_failedaction for debugging.