Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 437
Will Avatar asked Nov 22 '10 16:11

Will


3 Answers

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.*/
like image 121
milkovsky Avatar answered Nov 02 '22 17:11

milkovsky


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

like image 2
wajiw Avatar answered Nov 02 '22 17:11

wajiw


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.

like image 1
jhedstrom Avatar answered Nov 02 '22 19:11

jhedstrom