wordpress cron: using wp_mail function

Today I had to solve the problem, that my wordpress cron throws an exception like this when sending an email via wp_mail function inside a cron scheduled event function.

The wordpress cron was registered like that:

And the wordpress cron mechanism was triggered via Linux crontab:

Problem with wp_mail in wordpress cron

The problem was, that the PHP server variable $_SERVER[ 'SERVER_NAME' ] isn’t available when executed via crontab, unix shell as well as wp-cli wrapper. That’s the reason why the phpmailer  didn’t get the hostname for the from parameter, which results in trying to send  mail with “wordpress@” as from value. And that’s the trigger for the exception mentioned above.

Solution for wp_mail in wordpress cron

The solution was relatively simple, after determining what the real reason was. I just had to pass the server variable to PHP inside the crontab call.

The first part before the && sets the required environment variable. The second part stayed as it was and just calls the cron a usual.

Similar Problem

I had the same issue with wc-super-cache:

It was only a warning but hence I got all output via mail, it was really annoying. 😉
Once more I had to define an environment variable on my own:

As you can see, the missing environment variable was $_SERVER[ 'REQUEST_URI' ]  in that case.

Leave a Reply

Your email address will not be published. Required fields are marked *