I have following piece of code, which inserts usernames and other details of users in the database. After inserting the usernames I want to email them using wp_mail();. I am unable to do so. How can I do this?

$member_details->user_login = array_map( 'sanitize_text_field', $_POST['user_login'] );
$member_details->user_role = array_map( 'sanitize_text_field', $_POST['user_role'] );
$member_details->status = array_map( 'sanitize_text_field', $_POST['status'] );

$member_details_encode = wp_json_encode( $member_details );

  global $wpdb;

  $member_result = $wpdb->insert( 'wpxa_project_members',


              'project_id'     => $_SESSION['project_id'],
              'author_id'      => $post_author,
              'member_details' => $member_details_encode






2 Answers 2


Assuming that $member_details->user_login is already a user in the wp_users table, then you could use the following to get their email address:

$user = get_user_by( $member_details->user_login, 'login' );

From there, you have the user's email address and can use wp_mail() to email them:

$subject = "My email subject";
$message = "My message body...";
wp_mail( $user->user_email, $subject, $message );

Let us see what code you are trying. Assuming that the hook you have bound that function to is firing, you would insert this into your function, assuming you want to email the author.

wp_mail($to = $post_author, $subject = 'This is the subject', $message = 'This is the message');



$user = get_userdatabylogin($member_details->user_login);
$user_id = $user->ID;
wp_mail($user_id, 'This is the subject', 'This is the message');
  • I want all the users which are inserted into database through my code.. Actually I have created a dynamic add / remove fields in which I write usernames of the users. I want to mail them once inserted.
    – Minesh
    Jul 21, 2018 at 17:49
  • Check my edit above Jul 21, 2018 at 19:08
  • How can we mail through user_id... And how to get the emails of users in array.. Thanks LearntoExcel
    – Minesh
    Jul 21, 2018 at 19:16
  • wp_mail uses the user_id, you don't need the email. You can get the user_id using the code above. Jul 21, 2018 at 19:25
  • That's absolutely incorrect. wp_mail does not use user_id - so yes, you do need the email. Additionally, get_userdatabylogin() is a deprecated function and should no longer be used. You should be using get_user_by() instead.
    – butlerblog
    Feb 7, 2019 at 18:51

Your Answer

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

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