Need clarification on how to correctly call wp_mail()

I want to call wp_mail() from a non-template php file, but when I do so it fails and I don’t understand why. For example, let’s say I have a php file that consists of only this:

<?php
    echo 'hi';
    $mail_sent = wp_mail('example@example.com', 'subject', 'message');
    echo $mail_sent;
?>

If I load that php file directly in my browser, only “hi” will print. If I remove echo 'hi'; altogether, nothing is printed, which indicates to me that wp_mail() cannot be called in this particular context. However, if I add /* Template Name: SomeName */ to the file and create a new page using SomeName as its template, wp_mail() executes correctly. Clearly, I’m missing some key bit of information regarding how to correctly call wp_mail().

The reason I want to do this is because the theme I’m using came with a contact form that submits email via an ajax request roughly like this:

form.submit(function() {
    $j.ajax({
        type: 'GET',
        url: "http://www.example.com/wp-content/themes/themeX/send_mail.php",
        data: form.serialize(),
    });
});

Currently, send_mail.php calls the php mail() function which “works” but is extremely flaky. I want it to call wp_mail() so I can take advantage of this plugin which sends mail using a smtp server. So my question is: how can I get wp_mail() to work in this situation?

Thanks!

Solutions Collecting From Web of "Need clarification on how to correctly call wp_mail()"

The standalone script will not load WordPress, so it doesn’t have a wp_mail() function. WordPress has its own built-in Ajax handlers which you can leverage and have access to all WordPress functionality within those Ajax calls.

Alternatively, include the WordPress functions in your standalone script as follows

require_once('wp-blog-header.php'); 

I find the WP ajax functions are not always the best way to do things, so writing your own AJAX handler is quite valid.

wp_mail is a Pluggable Function so you should be able to call wp-includes/pluggable.php and then have the ablilty to use wp_mail().