Newly (programmatically created) blocked user gets access denied when resetting I'm trying to import some users into Drupal programmatically as blocked. I found two methods to do this: user_save and drupal_execute. However, the first one doesn't send notification email with the link to reset the password while the other method does send the mail, but when clicking the link I get a denied access.

I tried the code in 2 environments (Ubuntu and Windows) with one fresh installation. Here is the code I'm actually using:

// register a new user
$form_state['values']['name'] = 'username';
$form_state['values']['mail'] = 'mail@example.com';

// generate and assign password
$pass = user_password(8);
$form_state['values']['pass'] = array (
    'pass1' =&gt; $pass,
    'pass2' =&gt; $pass
);
$form_state['values']['status'] = 0; // add user as blocked
$form_state['values']['notify'] = 1; // send notification with reset link
$form_state['values']['op'] = t('Create new account');

// check if user it's not already imported
$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query($sql, $form_state['values']['name'] );
$data = db_result($result);
#print_r($data);
if (!$data) {  // if the user does not exist, add it
    drupal_execute('user_register', $form_state);
}


The user is added correctly in the database as blocked, I receive the notification email but when I click on the reset link I get access denied (which, by the way, it's appearing twice: all the elements of my theme twice with the error as content; really nasty bug... don't know why, anyone?)

Here goes the second code:

// user details
$users = array(
    'name' =&gt; 'username',
    'pass' =&gt; user_password(8),
    'mail' =&gt; 'mail@example.com',
    'access' =&gt; '0',
    'status' =&gt; 0,
    'notify' =&gt; 1,
    'timezone' =&gt; 7200,
    'init' =&gt; 'mail@example.com'
);

$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query( $sql, $users['name'] );
$data = db_result( $result );
#print_r($data);
if (!$data)
    user_save( NULL, $users, NULL );
}


With this method, everything works fine but I don't get the email, which is pointless because the users are blocked.

I don't know if this is a hard question (only for Drupal gurus), but I would appreciate any help.

Thank you!
I'm assuming that you are wanting users to click on a link in the registration email to validate the address (this is configurable in your user settings)

You should set status=1 in the user as this is the default behavior and if it is 0 the login link will not work.

If you look at user_register_submit() there is code in it to send out emails. 

I think you want 

$account =  user_save( NULL, $users, NULL );
if($account) {
  _user_mail_notify('register_admin_created', $account);
}
else {
// Error code
}


at the end of your second method.