0 Day Analytics – Mails Module Developer Documentation

Table of Contents

1. Overview & Architecture

The Mail Module provides comprehensive email monitoring, logging, and SMTP configuration for WordPress sites. It intercepts all emails sent via wp_mail(), records them to a custom database table with full metadata, and provides a WP_List_Table-based admin UI for browsing, searching, and managing email history.

Key Capabilities

  • Intercept and log all wp_mail() calls with full metadata (headers, attachments, backtrace)
  • Record delivery status (success/failure) with error messages
  • Capture CC, BCC, Reply-To headers and attachment details
  • Measure email delivery time (microsecond precision)
  • Auto-categorize emails (order, user, system, marketing, notification, transactional)
  • Detect and flag time-sensitive emails as non-resendable
  • Identify the originating plugin/theme via backtrace analysis
  • Configure external SMTP providers (Gmail, SES, Mailgun, SendGrid, etc.)
  • Compose and send new emails from the admin with rich-text editor
  • Resend previously logged emails
  • BuddyPress and Post SMTP plugin compatibility
  • Auto-clear schedule via cron job
  • Multisite support with per-site logging and filtering

Technology Stack

  • PHP 7.4+ (strict types)
  • WordPress WP_List_Table API
  • WordPress wp-api-fetch for REST interactions
  • PHPMailer (WordPress bundled) for SMTP delivery
  • WordPress TinyMCE editor for email composition
  • jQuery + Thickbox for detail modals

2. File Map

advanced-analytics/
├── classes/
│   └── vendor/
│       ├── controllers/
│       │   ├── class-wp-mail-log.php          — Email capture & logging engine
│       │   ├── class-mail-smtp-settings.php   — SMTP configuration & delivery
│       │   └── api/
│       │       └── class-endpoints.php        — REST API (mail body endpoint)
│       ├── entities/
│       │   └── class-wp-mail-entity.php       — Database schema & column definitions
│       ├── helpers/
│       │   └── class-ajax-helper.php          — AJAX endpoints (test email)
│       ├── lists/
│       │   ├── class-wp-mail-list.php         — WP_List_Table for mail log display
│       │   └── views/
│       │       └── class-wp-mail-view.php     — Page rendering, compose form, detail modal JS
│       └── settings/
│           └── settings-options/
│               └── mail-list.php              — Settings form fields (module + SMTP)
└──assets/
    ├── css/                                   — Stylesheets
    └── js/
        └── admin/
            └── aadvana-settings.js            — Test mail AJAX button handler

3. Admin Screens

3.1 Mail Log List

URL wp-admin/admin.php?page=advan_wp_mail
Menu Position Sub-menu under main plugin menu (index 4)
Capability manage_options
Controller WP_Mail_View::analytics_wp_mail_page()
List Table WP_Mail_List (extends Abstract_List)

UI Components

  • “Compose New” button in page header
  • Filter views – All | Successful | Unsuccessful | HTML | Text | With attachments
  • Plugin filter dropdown – filter by originating plugin
  • Site filter dropdown – filter by blog ID (multisite only)
  • Search box – full-text search across all columns (input name: s)
  • Sortable columns – All admin columns are sortable
  • Pagination – configurable via screen options (default: 20)
  • Row actions – Details | Resend | Delete (per row)
  • Bulk actions – Delete (for selected rows)
Screen layout:
┌──────────────────────────────────────────────────────────────┐
│  WP Mail Log                                [Compose New]    │
│──────────────────────────────────────────────────────────────│
│  All (156) | Successful (148) | Failed (8) | HTML | Text     │
│  [Plugin ▼] [Site ▼]                       [🔍 Search]       │
│──────────────────────────────────────────────────────────────│
│  ☐ Date ↕   | To        | Subject    | Category | Status     │
│  ☐ Today    | user@..   | Welcome    | user     | ✓          │
│     Details | Resend | Delete                                │
│  ☐ Today    | admin@..  | Error log  | system   | ✓          │
│     Details | Delete                                         │
│  ☐ Yest.    | cust@..   | Order #12  | order    | ✗          │
│     Details | Delete                                         │
│──────────────────────────────────────────────────────────────│
│  Bulk Actions [▼] [Apply]              ‹ 1 of 8 ›            │
└──────────────────────────────────────────────────────────────┘

3.2 Compose New Mail

URL wp-admin/admin.php?page=advan_wp_mail&action=new_mail&_wpnonce={nonce}
Form Action admin_post_advan_mail_new
Handler WP_Mail_View::new_mail()
Nonce advana_wp_mail_manager

Form Fields

Field Type Name Required Description
To email to Yes Recipient email(s), comma-separated
CC email cc No CC recipients, comma-separated
BCC email bcc No BCC recipients, comma-separated
Reply-To email reply_to No Reply-To email address
Subject text subject Yes Email subject line
Attachments file picker attachments No Files from WordPress Media Library
Message WP Editor message Yes Rich-text HTML editor (TinyMCE) with media buttons
Note: Composed emails are sent as text/html content type. They go through wp_mail(), so SMTP settings apply and the email is automatically logged.

3.3 Module Settings & SMTP

URL wp-admin/admin.php?page=advan_logs_settings#aadvana-options-tab-mail-list
Settings File classes/vendor/settings/settings-options/mail-list.php

Settings Sections

  1. Mail List Options – Enable module, auto-clear schedule
  2. External SMTP Provider – Full SMTP configuration
  3. Test Mail Delivery – Send test email button

4. Core Classes

4.1 ADVAN\Controllers\WP_Mail_Log

The email capture engine. Hooks into WordPress and third-party mail systems to intercept, analyze, and log all outgoing emails.

Hook Registration (init method)

PHP
<?php
// Core WordPress hooks
\add_filter( 'wp_mail', [ self::class, 'record_mail' ], PHP_INT_MAX );
\add_action( 'wp_mail_failed', [ self::class, 'record_error' ] );
\add_filter( 'wp_mail_content_type', [ self::class, 'detect_content_type' ] );
\add_action( 'phpmailer_init', [ self::class, 'extract_more_mail_info' ], PHP_INT_MAX );

// BuddyPress hooks
\add_action( 'bp_send_email', [ self::class, 'bp_record_mail' ] );
\add_filter( 'bp_email_use_wp_mail', [ self::class, 'bp_mail_check' ] );
\add_action( 'bp_send_email_failure', [ self::class, 'bp_record_error' ] );

// Post SMTP plugin hooks
\add_action( 'post_smtp_on_success', [ self::class, 'post_smtp_extract_from' ] );
\add_action( 'post_smtp_on_failed', [ self::class, 'post_smtp_extract_from' ] );

Key Methods

Method Return Description
record_mail($args) array Main capture method. Extracts all email data from wp_mail() filter args, captures backtrace, categorizes email, logs to database. Returns args unchanged (filter passthrough).
extract_more_mail_info($phpmailer) void Hooks into PHPMailer instance to extract From, To, Subject, Body, ContentType, Attachments, MailHeader. Calculates delivery time via microtime. Updates existing log entry.
record_error($wp_error) void Records email failure status (0) and error message from WP_Error.
detect_content_type($content_type) string Detects HTML vs plain-text content and stores the flag. Returns content type unchanged.
categorize_email($subject, $message) string Auto-categorizes email based on keyword detection.
can_resend_email($subject, $message) bool Checks for time-sensitive keywords to determine if resend is safe.
get_attachment_locations($attachments) array Resolves attachment file paths to media library IDs, URLs, icons, and MIME types.
calculate_attachment_stats($attachments) array Returns ['count' => int, 'total_size' => int].
bp_record_mail(...) void Captures BuddyPress emails before wp_mail() fallback.
post_smtp_extract_from($log) void Extracts sender info from Post SMTP plugin objects.

4.2 ADVAN\Controllers\Mail_SMTP_Settings

Manages external SMTP provider configuration and email delivery routing.

Constants

PHP
<?php
public const NONCE_NAME = ADVAN_PREFIX . 'mail'; // 'aadvana_mail'

Key Methods

Method Return Description
deliver_email_via_smtp($phpmailer) void Hooks into phpmailer_init (priority 999999). Configures PHPMailer for external SMTP: sets Host, Port, SMTPAuth, Username, Password, SMTPSecure, From, FromName, XMailer. Validates settings before connecting.
get_smtp_settings() array Returns all configured SMTP options from the database.
validate_smtp_settings($settings) bool Validates that required SMTP fields (host, port) are present and port is in valid range (1–65535).

SMTP Delivery Flow

PHP
<?php
// Hooks at a very high priority to override other plugins
add_action( 'phpmailer_init', [ self::class, 'deliver_email_via_smtp' ], 999999 );

public static function deliver_email_via_smtp( $phpmailer ) {
    $settings = self::get_smtp_settings();
    
    // Validate before configuring
    if ( ! self::validate_smtp_settings( $settings ) ) {
        return;
    }

    $phpmailer->isSMTP();
    $phpmailer->Host       = $settings['smtp_host'];
    $phpmailer->Port       = $settings['smtp_port'];
    $phpmailer->SMTPSecure = $settings['encryption_type'];
    $phpmailer->SMTPAuth   = ! empty( $settings['smtp_username'] );
    $phpmailer->Username   = $settings['smtp_username'];
    $phpmailer->Password   = $settings['smtp_password'];
    
    // Optional From override
    if ( ! empty( $settings['from_email'] ) ) {
        $phpmailer->From     = $settings['from_email'];
        $phpmailer->FromName = $settings['from_email_name'];
    }
    
    // SSL bypass for development
    if ( $settings['smtp_bypass_ssl_verification'] ) {
        $phpmailer->SMTPOptions = [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true,
            ],
        ];
    }
}

4.3 ADVAN\Lists\WP_Mail_List

Extends Abstract_List (which extends WP_List_Table). Handles the mail log admin list table rendering, column management, sorting, searching, filtering, and bulk operations.

Constants

PHP
<?php
const WP_MAIL_MENU_SLUG     = 'advan_wp_mail';
const PAGE_SLUG             = ADVAN_INNER_SLUG . '_page_advan_wp_mail';
const SCREEN_OPTIONS_SLUG   = 'advanced_analytics_wp_mail_list';
const SEARCH_INPUT          = 's';
const NEW_ACTION            = 'advan_mail_new';
const NONCE_NAME            = 'advana_wp_mail_manager';
const SITE_ID_FILTER_ACTION = 'filter_site_id';
const PLUGIN_FILTER_ACTION  = 'aadvana_page_advan_wp_mail_filter_plugin';

Key Methods

Method Description
menu_add() Registers the admin submenu page
hooks_init() Initializes WordPress hooks (screen options, columns)
process_actions_load() Processes bulk actions on load-{page}
prepare_items() Populates the table with data from database
fetch_table_data($args) Retrieves and filters mail log records from the entity
get_bulk_actions() Returns available bulk actions (Delete)
handle_table_actions() Executes selected bulk action
manage_columns($columns) Defines visible columns
format_column_value($item, $column) Formats cell value for display
truncate_wp_mail_table() Cron callback to truncate the mail log table
handle_resend_email() Processes email resend via admin_post

4.4 ADVAN\Lists\Views\WP_Mail_View

Handles page rendering for mail screens (list, compose) and includes inline JavaScript for the detail modal.

Key Methods

Method Description
analytics_wp_mail_page() Main page router – renders list or compose form based on $_REQUEST['action']
new_mail() Handles compose form submission via admin_post
plugin_filter_action() Processes plugin filter dropdown selection
site_filter_action() Processes site filter dropdown selection (multisite)

Detail Modal JavaScript

The view class injects inline JavaScript that:

  • Intercepts “Details” link clicks
  • Fetches mail details via REST API: /aadvana/v1/mail_body/{id}/
  • Renders the email in a Thickbox modal with metadata table
  • Provides copy-to-clipboard and Web Share API buttons
  • Color-codes category badges
  • Formats file sizes (bytes → KB → MB)
  • Displays delivery time in milliseconds

4.5 ADVAN\Entities\WP_Mail_Entity

Database entity class. Defines the mail log table schema, column definitions, and provides static methods for data access.

Table Name

PHP
<?php
$table_name = $wpdb->prefix . 'advan_wp_mail_log';

Key Methods

Method Return Description
get_column_names_admin() array Returns column name→label map for admin list table
get_items($args) array Query builder for fetching mail records with filtering, sorting, pagination
insert($data) int|false Insert a new mail log entry
update($id, $data) bool Update an existing mail log entry
delete($id) bool Delete a mail log entry by ID
get_item($id) array|null Get a single mail log entry
create_table() void Creates the database table on plugin activation

5. Data Model & Database Schema

Mail log entries are stored in the {prefix}advan_wp_mail_log table:

Column Type Since Description
id BIGINT UNSIGNED AUTO_INCREMENT 1.0 Primary key
blog_id INT 3.6.3 Multisite blog ID
plugin_slug VARCHAR(255) 4.1.1 Originating plugin/theme slug
time DOUBLE 1.0 Unix timestamp (when email was logged)
email_to TEXT 1.0 Recipient address(es)
email_from TEXT 1.0 Sender address
email_cc TEXT 4.7.1 CC recipients
email_bcc TEXT 4.7.1 BCC recipients
email_reply_to TEXT 4.7.1 Reply-To address
subject TEXT 1.0 Email subject
message MEDIUMTEXT 1.0 Email body content
message_size INT UNSIGNED 4.7.1 Body size in bytes
total_size INT UNSIGNED 4.7.1 Total size (body + attachments)
backtrace_segment MEDIUMTEXT 1.0 JSON-encoded backtrace for debugging
status BOOL 1.0 1 = successful, 0 = failed
is_html BOOL 1.0 1 = HTML, 0 = plain text
error TEXT 1.0 Error message (if failed)
attachments MEDIUMTEXT 1.0 JSON array of attachment data
attachment_count TINYINT UNSIGNED 4.7.1 Number of attachments
attachment_total_size INT UNSIGNED 4.7.1 Total attachment size in bytes
additional_headers TEXT 1.0 JSON of extra email headers
delivery_time DECIMAL(10,6) 4.7.1 Time to send in seconds
email_category VARCHAR(50) 4.7.1 Auto-detected category
can_resend BOOL 4.7.1 1 = safe to resend, 0 = time-sensitive

Database Indexes

SQL
PRIMARY KEY (id)
KEY email_category (email_category)
KEY status (status)

Attachment JSON Format

JSON
[
  {
    "id": 123,
    "url": "https://example.com/wp-content/uploads/file.pdf",
    "src": "icon_url",
    "alt": "File name",
    "mime_type": "application/pdf"
  },
  {
    "id": -1,
    "url": "path/to/file.txt",
    "alt": "file.txt",
    "note": "Attachment not in media library"
  }
]

6. Mail Capture Pipeline

The following diagram shows the sequence of hooks and methods involved in capturing an email:

wp_mail() called
    │
    ├─ 1. wp_mail filter (PHP_INT_MAX) ──→ record_mail()
    │      ├── Extract: to, subject, message, headers, attachments
    │      ├── Parse headers → CC, BCC, Reply-To
    │      ├── Backtrace analysis → identify originating plugin
    │      ├── categorize_email() → detect category
    │      ├── can_resend_email() → check time-sensitivity
    │      ├── get_attachment_locations() → resolve file details
    │      ├── calculate_attachment_stats() → count + sizes
    │      └── INSERT into advan_wp_mail_log
    │
    ├─ 2. wp_mail_content_type filter ──→ detect_content_type()
    │      └── Store is_html flag
    │
    ├─ 3. phpmailer_init action (PHP_INT_MAX) ──→ extract_more_mail_info()
    │      ├── Access PHPMailer properties via closure
    │      ├── Extract: From, FromName, To, Subject, Body, ContentType
    │      ├── Extract: Attachment array, MailHeader
    │      ├── Calculate delivery time (microtime delta)
    │      └── UPDATE existing log entry with enriched data
    │
    └─ 4. wp_mail_failed action ──→ record_error()
           └── UPDATE status=0, store error message
Order matters: record_mail() fires first (as a wp_mail filter at PHP_INT_MAX), creating the initial database entry. Then extract_more_mail_info() fires later (via phpmailer_init) to enrich the record with additional PHPMailer data.

7. Email Categorization System

Emails are auto-categorized based on keyword detection in the subject and message body. The system checks in priority order, returning the first match:

Category Keywords Checked (case-insensitive) Typical Sources
order order, purchase, invoice, receipt, payment, checkout, cart WooCommerce, EDD, other e-commerce
user welcome, registration, account, profile, username, login User management, registration emails
system error, critical, warning, debug, admin, update available, backup System alerts, update notfications
marketing newsletter, promotion, sale, discount, offer, subscribe, unsubscribe Newsletter plugins, marketing plugins
notification notification, alert, reminder, comment, reply, mention Comment notifications, social features
transactional password, reset, verify, confirmation, code, token Password resets, email verification
general (default when no keywords match) Any other email

8. Resend Logic & Safety

The module includes a safety mechanism to prevent resending time-sensitive emails.

Time-Sensitive Keywords (prevent resend)

PHP
<?php
$blocked_keywords = [
    'password reset',  'verification code',
    'verify your',     'confirm your',
    'one-time',        'expires',
    'expiring',        '2fa',
    'two-factor',      'authentication code',
    'otp',
];

Resend Flow

URL admin.php?action=resend_email&mail_id={id}&_wpnonce={nonce}
Handler WP_Mail_List::handle_resend_email()
Nonce resend_email_{id}

The handler reconstructs the original email from stored data:

  1. Retrieves mail record from database by ID
  2. Rebuilds headers array from stored CC, BCC, Reply-To
  3. Restores attachment paths
  4. Calls wp_mail() with all original parameters
  5. The re-sent email is automatically logged as a new entry

9. AJAX Handlers

Send Test Email AJAX

Action wp_ajax_aadvana_send_test_email
Handler Ajax_Helper::send_test_email()
Nonce Mail_SMTP_Settings::NONCE_NAME (aadvana_mail)
Parameters email (string, sanitized email address)

Implementation Details

  • Validates nonce and capability
  • Sanitizes the email address via sanitize_email()
  • Selects a random fun test message from predefined templates
  • Includes the site URL and current date/time in the test email body
  • Sets Content-Type: text/html header
  • Sends via wp_mail() which routes through SMTP if configured
  • Returns JSON success/error response

JavaScript Example

JavaScript
jQuery(document).on('click', '#mail_send_test_ajax', function(e) {
    e.preventDefault();
    
    var email = jQuery('#test_email_address').val();
    
    jQuery.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
            action: 'aadvana_send_test_email',
            email: email,
            _wpnonce: aadvana_settings.nonce
        },
        success: function(response) {
            if (response.success) {
                alert('Test email sent successfully!');
            } else {
                alert('Failed: ' + response.data);
            }
        }
    });
});

10. REST API Endpoints

Get Mail Body GET

Endpoint /aadvana/v1/mail_body/{id}/
Method GET (WP_REST_Server::READABLE)
Permission manage_options capability
Parameter id (integer, required) – the mail log entry ID

Success Response

JSON
{
    "success": true,
    "mail_body": "<html>...full email content...</html>",
    "email_to": "[email protected]",
    "email_from": "[email protected]",
    "email_cc": "[email protected]",
    "email_bcc": "[email protected]",
    "email_reply_to": "[email protected]",
    "subject": "Welcome to our site",
    "email_category": "user",
    "additional_headers": "{\"Content-Type\": \"text/html\"}",
    "message_size": 2048,
    "message_size_formatted": "2 KB",
    "total_size": 15360,
    "total_size_formatted": "15 KB",
    "attachment_count": 1,
    "attachment_total_size": 13312,
    "attachment_total_size_formatted": "13 KB",
    "delivery_time": 0.125,
    "can_resend": 1,
    "attachments": "<ul>...attachment HTML...</ul>"
}

Error Response

JSON
{
    "code": "empty_row",
    "message": "No record found.",
    "data": {
        "status": 400
    }
}

cURL Example

Shell
curl -X GET \
  "https://example.com/wp-json/aadvana/v1/mail_body/42/" \
  -H "X-WP-Nonce: <nonce>" \
  --cookie "wordpress_logged_in_xxx=..."

JavaScript (wp-api-fetch) Example

JavaScript
wp.apiFetch({
    path: '/aadvana/v1/mail_body/42/',
}).then(response => {
    if (response.success) {
        console.log('Subject:', response.subject);
        console.log('Category:', response.email_category);
        console.log('Delivery time:', response.delivery_time, 'sec');
    }
}).catch(err => {
    console.error('Failed to fetch mail body:', err.message);
});

11. Hooks & Filters

Filters Used FILTER

Filter Priority Description
wp_mail PHP_INT_MAX Main email capture point. Extracts all email data for logging. Returns args unchanged (passthrough).
wp_mail_content_type default Detects HTML vs plain-text content type for the is_html flag.
bp_email_use_wp_mail default BuddyPress filter to check if emails fall back to wp_mail().

Actions Used ACTION

Action Priority Description
phpmailer_init PHP_INT_MAX Extracts detailed PHPMailer properties to enrich the log entry (From, headers, delivery time).
phpmailer_init 999999 SMTP delivery configuration (via Mail_SMTP_Settings::deliver_email_via_smtp()).
wp_mail_failed default Records failure status and error message.
bp_send_email default Captures BuddyPress emails before they’re sent.
bp_send_email_failure default Logs BuddyPress email failures.
post_smtp_on_success default Post SMTP plugin compatibility – extracts sender info.
post_smtp_on_failed default Post SMTP plugin failure handling.
admin_post_advan_mail_new Handles compose form submission.
admin_post_resend_email Handles email resend action.

12. SMTP Internals

The SMTP implementation uses WordPress’s bundled PHPMailer library. When SMTP settings are configured and the module is enabled, the plugin hooks into phpmailer_init at priority 999999 (intentionally very high to override other plugins).

Configuration Hierarchy

TEXT
wp_mail() called
    │
    └─ phpmailer_init action fires
           │
           ├─ Priority 10-999998: Other plugins' PHPMailer hooks
           │
           ├─ Priority 999999: Mail_SMTP_Settings::deliver_email_via_smtp()
           │     ├── Validate settings (host + port required)
           │     ├── Set isSMTP() mode
           │     ├── Configure Host, Port, Auth, Encryption
           │     ├── Set custom XMailer header
           │     ├── Override From/FromName (if configured)
           │     └── Apply SSL bypass (if enabled)
           │
           └─ Priority PHP_INT_MAX: WP_Mail_Log::extract_more_mail_info()
                 └── Extract enriched data for logging

WordPress Options (SMTP)

Option Key Type Description
advan_smtp_host string SMTP server hostname
advan_smtp_port int SMTP port (1–65535, default 587)
advan_encryption_type string '' (none), 'ssl', or 'tls'
advan_smtp_username string Auth username
advan_smtp_password string Auth password
advan_from_email string Override From address
advan_from_email_name string Override From display name
advan_smtp_bypass_ssl_verification bool Skip SSL certificate validation

13. Settings Reference

Settings are rendered using the plugin’s Settings::build_option() builder. The mail settings are on the Mail Options tab within the main settings page.

PHP
<?php
// Check if mail module is enabled
$enabled = Settings::get_option( 'wp_mail_module_enabled' );

// Get the auto-clear schedule
$schedule = Settings::get_option( 'advana_mail_logging_clear' );

// Get SMTP configuration
$smtp_host = Settings::get_option( 'smtp_host' );
$smtp_port = Settings::get_option( 'smtp_port' );

// Check SMTP encryption type
$encryption = Settings::get_option( 'encryption_type' );

Auto-Clear Cron Job

PHP
<?php
// Hook name for the auto-clear cron
$hook = 'aadvana_mail_logging_clear';

// Callback
add_action( 'aadvana_mail_logging_clear', [
    WP_Mail_List::class,
    'truncate_wp_mail_table'
]);

14. List Table Columns & Sorting

Columns

Key Header Sortable Description
cb No Bulk selection checkbox
time Date Yes ↑ Timestamp with Today/Yesterday formatting
email_to To Yes Recipient address(es)
email_from From Yes Sender address
email_cc CC Yes Carbon-copy recipients
email_bcc BCC Yes Blind carbon-copy recipients
email_reply_to Reply-To Yes Reply-To address
subject Subject Yes Email subject line
message_size Size Yes Body size in bytes
email_category Category Yes Auto-detected category with colored badge
is_html Format Yes HTML or Text format indicator
attachments Attachments Yes List of attached files
attachment_count Att. Count Yes Number of attachments
delivery_time Delivery Time Yes Send duration in milliseconds
plugin_slug Plugin Yes Originating plugin/theme slug

Filter Views

View Filter Criteria
All No filter
Successful status = 1
Unsuccessful status = 0
HTML is_html = 1
Text is_html = 0
With attachments Non-empty attachments JSON

The search box performs full-text search across all columns. Input parameter: s.

15. Bulk & Row Actions

Row Actions (per mail entry)

Action Method Description
Details REST API modal Opens Thickbox modal with full email content and metadata via /aadvana/v1/mail_body/{id}/
Resend admin_post_resend_email Re-sends the email. Hidden for time-sensitive emails (can_resend = 0).
Delete Admin page redirect Permanently removes the log entry from the database

Bulk Actions

Action Description
Delete Delete all selected mail log entries

Security

  • Nonce verification for all form submissions
  • Capability check: manage_options required
  • Resend nonce: resend_email_{id} (unique per entry)

16. Third-Party Compatibility

BuddyPress

Full support via dedicated hooks:

  • bp_send_email — Captures BuddyPress emails before they’re routed
  • bp_email_use_wp_mail — Checks if BuddyPress falls back to wp_mail()
  • bp_send_email_failure — Logs BuddyPress email failures

Post SMTP

Compatibility hooks for the Post SMTP plugin:

  • post_smtp_on_success — Extracts “From” address after successful Post SMTP delivery
  • post_smtp_on_failed — Extracts “From” address after Post SMTP failures
Note: When Post SMTP is active and managing email delivery, Advanced Analytics still captures the email details. However, the SMTP settings in Advanced Analytics should be disabled to avoid conflicts — let Post SMTP handle delivery while Advanced Analytics handles logging.

WooCommerce

WooCommerce emails sent via wp_mail() are automatically captured and categorized as order based on keyword detection in the subject/body.

17. Code Examples

Example 1: Check if Mail Module is Enabled

PHP
<?php
use ADVAN\Helpers\Settings;

$mail_enabled = Settings::get_option( 'wp_mail_module_enabled' );

if ( $mail_enabled ) {
    // Mail module is active — emails are being logged
}

Example 2: Fetch a Mail Record via REST API (PHP)

PHP
<?php
// Programmatic REST API call within WordPress
$request = new \WP_REST_Request( 'GET', '/aadvana/v1/mail_body/42/' );
$response = rest_do_request( $request );

if ( ! $response->is_error() ) {
    $data = $response->get_data();
    error_log( 'Email subject: ' . $data['subject'] );
    error_log( 'Delivery time: ' . $data['delivery_time'] . 's' );
    error_log( 'Category: ' . $data['email_category'] );
}

Example 3: Query Mail Log Entries Directly

PHP
<?php
use ADVAN\Entities\WP_Mail_Entity;

// Get all failed emails from the last 24 hours
$failed_mails = WP_Mail_Entity::get_items([
    'status'   => 0,
    'per_page' => 50,
    'orderby'  => 'time',
    'order'    => 'DESC',
]);

foreach ( $failed_mails as $mail ) {
    printf(
        "To: %s | Subject: %s | Error: %s\n",
        $mail['email_to'],
        $mail['subject'],
        $mail['error']
    );
}

Example 4: Send Test Email via AJAX (JavaScript)

JavaScript
const formData = new FormData();
formData.append('action', 'aadvana_send_test_email');
formData.append('email', '[email protected]');
formData.append('_wpnonce', aadvana_settings.nonce);

fetch(ajaxurl, {
    method: 'POST',
    body: formData,
})
.then(r => r.json())
.then(data => {
    if (data.success) {
        console.log('Test email sent!');
    } else {
        console.error('Send failed:', data.data);
    }
});

Example 5: Access SMTP Settings Programmatically

PHP
<?php
use ADVAN\Controllers\Mail_SMTP_Settings;

$settings = Mail_SMTP_Settings::get_smtp_settings();

if ( ! empty( $settings['smtp_host'] ) ) {
    error_log( sprintf(
        'SMTP configured: %s:%d (%s)',
        $settings['smtp_host'],
        $settings['smtp_port'],
        $settings['encryption_type'] ?: 'none'
    ));
}

Example 6: Multisite – Filter Emails by Site

PHP
<?php
use ADVAN\Entities\WP_Mail_Entity;

// Get emails for blog ID 3
$site_emails = WP_Mail_Entity::get_items([
    'blog_id'  => 3,
    'per_page' => 25,
]);

echo count( $site_emails ) . ' emails from site #3';
Need User Guide documentation?
See Mails Module User Guide for more details about configuration, practical usage and information.
← Mails Module - User Guide Requests Module — User Guide →
Share this page
Back to top