How do I send an email notification when programatically creating a Drupal user?

13,456

Solution 1

You could use Rules. You can add an action to be fired when user is created.

Solution 2

You can use the standard _user_mail_notify() function from the Drupal core's "User" module.

   // Create user.
   $new_user = array(
      'name' => $username,
      'pass' => $password, 
      'mail' => $email,
      'status' => 1,
      'init' => $email,
      'roles' => array(DRUPAL_AUTHENTICATED_RID => TRUE),
    );  
   $account = user_save(NULL, $new_user);
   // Set operation.
   $op = 'register_no_approval_required';
   // Send an email.
   _user_mail_notify($op, $account);

There are different values of $op:

 /* @param $op
 *   The operation being performed on the account. Possible values:
 *   - 'register_admin_created': Welcome message for user created by the admin.
 *   - 'register_no_approval_required': Welcome message when user
 *     self-registers.
 *   - 'register_pending_approval': Welcome message, user pending admin
 *     approval.
 *   - 'password_reset': Password recovery request.
 *   - 'status_activated': Account activated.
 *   - 'status_blocked': Account blocked.
 *   - 'cancel_confirm': Account cancellation request.
 *   - 'status_canceled': Account canceled.*/

Solution 3

Have you implemented user_register_notify? http://drupal.org/project/user_register_notify

Here are the instructions on how to set it up: http://drupal.org/node/97183/cvs-instructions/HEAD

Solution 4

If you want to mimic how Drupal core handles this, take a look at user_register_submit(). That is the function that reacts to the checkbox you mention above, and if notifications are desired, passes the saved user object into _user_mail_notify(), which handles the sending of the message.

Share:
13,456

Related videos on Youtube

Will
Author by

Will

Updated on June 04, 2022

Comments

  • Will
    Will almost 2 years

    I am trying to create a user using code. I have the following that created the user. It however does not send an email to the user saying that the account has been created. How can I do that?

    $newUser = array(
      'name' => 'username',
      'pass' => 'password', // note: do not md5 the password
      'mail' => 'email address',
      'status' => 1,
      'init' => 'email address'
    );           
    user_save(null, $newUser);
    
  • user25794
    user25794 over 5 years
    Accepted answer?? What if rules isn't installed.

Related