2

I'm trying to test wp_mail() in my local. When I var dump wp_mail,I get Boolean false.This is my code

    $to = "[email protected]";
    $subject = 'my subject';
    $message = 'I would like to work with you';
    $headers = '';


    $sent_message = wp_mail( $to, $subject, $message, $headers);
    var_dump($sent_message); // i get boolean false here.
    if ( $sent_message ) {
        echo 'The test message was sent. Check your email inbox.';
    } else {
        echo 'The message was not sent!'; //this gets printed in d end.
    }

Any help would be appreciated.

3 Answers 3

5

wp_mail() falls back to php's mail() function which requires a configured MTA (Message Transfer Agent) on your host. So either you install and configure such a MTA. If you're running a Linux like OS, SSMTP is an easy solution on which you can use any mail-provider to send your system mails via SMTP. Another MTA would be Sendmail, a full featured, yet difficult to configure MTA.

Or you simply use a plugin like WP Mail SMTP which implements a direct SMTP connection in PHP and bypass the mail() usage.

1
  • If you just want to test mail functionality while developing you can use mailcatcher: mailcatcher.me Didn't test it on windows - but on Mac os it running. On other linux os it should work as well.
    – Luckyfella
    Aug 24, 2017 at 19:56
5

If anybody stumbles across this old question:

In my case, the reason was, I gave the site at localhost a name without a top-level domain. e.g. "mysite" (instead of "mysite.com"). So, WordPress assumed the "From" address to be "wordpress@mysite".

Phpmailer (which is called by wp_mail) then raised the error: "Invalid address: (From): wordpress@mysite"

Solution was to explicitly set the from address via the header:

    $headers[] = 'From: Wordpress<[email protected]>';
    $sent_message = wp_mail( $to, $subject, $message, $headers );

Then wp_mail worked.

0

Expanding on Ronni's helpful answer, here's how you can override the From: address for all outgoing mail:

if (defined('WP_CLI')) {
    WP_CLI::add_wp_hook('wp_mail_from', function () {
        return '[email protected]';
    });
} else {
    add_filter('wp_mail_from', function () {
        return '[email protected]';
    });
}

For my local development environment, I found it useful to place it in wp-config.php, at the very bottom, after require_once ABSPATH . 'wp-settings.php';.

Added a workaround for wp-cli, since it doesn't provide add_filter() like WP would normally do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.