I developed custom module to create users.

And I setup config account setting "Require email verification" to "Require a verification email, but let users set their password directly on the registration form" using the User registration password module.

When registering via default forms it is works fine (email verification sent to user). But when I created user via custom module API the email verification doesn't send to user.

This is my code:

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$user = User::create();
$user->set('init', $data->email);
$user->set('status', 0);
$user->set('langcode', $language);
$user->set('preferred_langcode', $language);
$user->set('preferred_admin_langcode', $language);
$user->set('langcode', $language);
$user->set("field_name", $data->nama_ibu);
$user->set("field_dob", $data->dob_year . '-' . $data->dob_month . '-' . $data->dob_date);
$user->set("field_phone", $data->phone);
// $user->activate();
$result = $user->save();

_user_mail_notify('register_no_approval_required', $user);
  • 1
    You can't create anonymous users. Anonymous users are guests on your site. With no account. Regular non-logged-in visitors. What's that _user_mail_notify function? Where is it coming from? What does it do exactly and how? Please update your question. Many thanks
    – leymannx
    Apr 22, 2021 at 7:42
  • 2
    @leymannx: _user_mail_notify() is a normal core Drupal function. Yes, even in D9. See the API docs.
    – anonymous
    Apr 22, 2021 at 7:49
  • @leymannx thank you for fixing my question... i called _user_mail_notify on my custom module and reference to core user.module. I saw this code and replicate from core/modules/user/src/RegisterForm.php. I don't know this code is work or not. I think its does't work, because when i remove this code and i replace with some code for updated user status to 1 after saving data first time the email has been send. is there any other solution for sending an email activation link on custom module? Apr 22, 2021 at 9:23
  • Code is working - I have checked, except custom fields. So check: 1. email in site is working 2. spam folder in your mail. 3. errors or warnings on your code.
    – Nikit
    Apr 25, 2021 at 2:05


Your Answer

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

Browse other questions tagged or ask your own question.