Check to check if wp_mail is working properly?

WordPress relies on the PHPMailer class to send email through PHP’s mail function.

Since PHP’s mail function returns very little information after execution (only TRUE or FALSE), I suggest temporarily stripping down your mv_optin_mail function to a minimum in order to see if the wp_mail functions works.

Example:

$mailResult = false;
$mailResult = wp_mail( '[email protected]', 'test if mail works', 'hurray' );
echo $mailResult;

Since you’ve tested PHP’s mail function already, the mail should arrive.

If it does not, the problem lies in the other statements of your function or in the PHPMailer class.

In cases like this, I usually rename my function to something like:

function mv_optin_mail_backup( $id, $data ) {

And add a temporary function with the same name to mess around with like so:

function mv_optin_mail( $id, $data ) {
    $mailResult = false;
    $mailResult = wp_mail( '[email protected]', 'test if mail works', 'hurray' );
    echo $mailResult;
}

When I have figured out what the problem is, I start using the backup version again.

To send a mail using PHPMailer directly you can do something like this (not for production, just for debugging):

add_action( 'phpmailer_init', 'my_phpmailer_example' );
function my_phpmailer_example( $phpmailer ) {
    $phpmailer->isSMTP();
    //$phpmailer->Host="smtp.example.com";
    //    $phpmailer->SMTPAuth = true; // Force it to use Username and Password to authenticate
    $phpmailer->Port = 25;
    //    $phpmailer->Username="yourusername";
    //    $phpmailer->Password = 'yourpassword';

    // Additional settingsā€¦
    //$phpmailer->SMTPSecure = "tls"; // Choose SSL or TLS, if necessary for your server
    $phpmailer->setFrom( "[email protected]", "From Name" );
    $phpmailer->addAddress( "[email protected]", "Your name" );
    $phpmailer->Subject    = "Testing PHPMailer";           
    $phpmailer->Body     = "Hurray! \n\n Great.";
    if( !$phpmailer->send() ) {
        echo "Mailer Error: " . $phpmailer->ErrorInfo;
    } else {
        echo "Message sent!";
    }                       

}       

Leave a Comment