Search code examples
phpwordpressphpmailer

how to load user_email from database and post it in $to of Php wp_mail() function


I am trying to send birthday mail to the registered user using the PHP wp_mail() function of wordpress. However, I am not able to send the email. Please into the code below:


# Get user ID
$id = get_current_user_id();

global $wpdb;

//query to extract  birthdate from database 
$result = $wpdb->get_results("SELECT um.meta_value FROM `wp_usermeta` AS um WHERE um.user_id = $id AND um.meta_key = 'birth_date'");

//query to extract email from database
$query= $wpdb->get_results("SELECT u.user_email FROM `wp_users` AS u WHERE u.ID = $id");


//load data from database and store it in user_name variable

foreach ($query as $row1) {
    $user_name =  $row1->user_email;
       
        
}
//birth_date 
$newDate = date("d-m", strtotime($birth_date ));  
//echo "birth date format is: ".$newDate;  

//present date
//$now = time();
//$newNow= date("d-m", strtotime($now));  
$newNow = date("d-m");
//echo "Today date format is: ".$newNow; 


if ($newDate == $newNow) { 
    
    $to = $user_name;
    $subject = 'Happy Birthday';
       

    $body = 'Hello Gaurav';
    wp_mail( $to, $subject,$body );

 
}

?>


In the code above I tried putting $to=$user_name in the $to section, it does not send emails to the registered user. However, If I put an entire email address manually i.e. $to= "[email protected]" the xyz user receives emails successfully.


Solution

  • I revised your code. you should check email is empty or not. try the below code.

    For email you can get user using get_user_by()

    $user = get_user_by( 'id', get_current_user_id() );
    

    To retrieve user meta you can use get_user_meta() function.

    $birth_date = get_user_meta( $user->ID, 'birth_date', true );
    
    function sent_birthday_mail(){
    
        $user = get_user_by( 'id', get_current_user_id() );
    
        if ( $user ) {
            $email      = $user->user_email;
            $birth_date = get_user_meta( $user->ID, 'birth_date', true );
            $birth_date = date("d-m", strtotime( $birth_date ) );
            $today_date = date("d-m");
    
            if ( $email != '' && $today_date == $birth_date) { 
                $to      = $email;
                $subject = 'Happy Birthday';
                $body    = 'Hello '.$user->first_name;
                if( wp_mail( $to, $subject, $body ) ){
                    echo "sent";
                }
            }
        }
    
    }
    add_action( 'init', 'sent_birthday_mail', 10, 1 );
    

    Also, you can check wp_mail error using WP wp_mail_failed action hook.

    // show wp_mail() errors
    add_action( 'wp_mail_failed', 'onWPMailError', 10, 1 );
    function onWPMailError( $wp_error ) {
        echo "<pre>"; print_r($wp_error); echo "</pre>";
    }