Change user's email without verification

AI-generated summary

Users are seeking ways to change a user’s email address in Discourse without requiring verification, particularly for admin use cases. carlokok initiates the discussion, asking if admins can bypass email verification. elijah suggests using the Rails console to directly update the email via User.find_by(...).update(...). JagWaugh references a meta topic recommending deactivating, changing, then reactivating the user — though this still triggers a confirmation email. skodali reports that even this method still requires confirmation and asks if it’s possible via API for bulk updates. schungx provides updated console commands targeting the UserEmail model: UserEmail.find_by(email: "old@example.com").update(email: "new@example.com"). However, Iceman encounters a NoMethodError, likely because the email wasn’t found — possibly due to typos or changes in schema. mint_saxon confirms the command works if the email matches exactly. codinghorror suggests server time drift may cause expired verification links. Admins also report rate-limiting errors when attempting email changes, even after a single attempt. The consensus leans toward using the Rails console with UserEmail for direct, unverified updates — but accuracy in email matching is critical. API-based solutions for bulk changes remain unconfirmed.

Maybe I’m missing something obvious, but I cannot find it. As an admin, can I change someone’s email address without them having to verify it?

Off-hand, I’d guess something like this would work:

cd /var/discourse
./launcher enter app
rails c
User.find_by(email: "chowder@mmmm.fooo").update(email: "bisque@soup.mmmm")
exit
exit

That’s console access, obviously.

I vaguely recall another topic here about this exact situation; try some searches.

Try this, the verification mail goes out, but they don’t have to respond to it:

Too late for me to edit that now, but it should be deactivate, change, reactivate iirc.

No problem I made it a wiki.

I am a new discourse user and I ran into the same issue. When I try the same approach (deactivate the user, update the email address, and then activate the user) it sending an email to confirm and it is only updating the email address after clicking the confirm email link. Is there a way to avoid this? I am using the API to do all the three actions.

There has been a change in the way emails are stored in the database.

The following commands should work:

cd /var/discourse
sudo ./launcher enter app
rails c

UserEmail.find_by(email: "oid@example.com").update(email: "new@example.com")

This will work fine but I am trying to do this via API as I will have to update multiple email addresses on a daily basis. Is it possible to do this via API?

Массивная некромантия, да, но я столкнулся с похожей проблемой, и раз поиск привёл меня сюда, возможно, стоит обновить команды с учётом этого опыта.

Моя ситуация следующая:

  • Некоторые пользователи пытались изменить свой основной адрес электронной почты.
  • Они утверждают, что это не сработало. Они получали письмо для подтверждения, но при переходе по ссылке всегда появлялось сообщение «Истёк срок действия/Не работает».
  • Я захожу как администратор и меняю указанный адрес, редактируя их профиль.
  • Теперь основной адрес электронной почты находится в статусе «ожидает подтверждения/верификации».
  • Пользователи не получают никаких писем с подтверждением.
  • Неважно, сколько раз я нажимаю опцию «повторно отправить письмо с подтверждением/валидацией» в их профиле, письмо не отправляется (проверил в разделе Администратор/Электронная почта — исходящих писем нет. Иронично, что если я нажму отправить им «письмо для сброса пароля», то оно отправляется).

Дело в том, что если любой из этих пользователей очистит файлы cookie и т. д., он больше не сможет получить доступ к своему аккаунту (это уже происходит прямо сейчас). Поэтому я попробовал следующее:

Но я получаю ошибку NoMethodError: undefined method `update' for nil:NilClass. Возможно, поля изменились снова за последние два года? :stuck_out_tongue:

Любая помощь будет приветствоваться.

P.S. Также, если я пытаюсь изменить адрес электронной почты на другой или на старый, теперь я (администратор) получаю сообщение «Вы выполнили это действие слишком много раз. Пожалуйста, попробуйте позже». Сколько времени должно пройти и почему для администратора установлено ограничение на частоту смены адресов электронной почты, если я сделал это только один раз? Возможно, я что-то сделал не так и не заметил этого :facepalm:

Значит, доставка писем работает, возможно, время на сервере не совпадает или указано неверно? Если время на сервере не совпадает, такое может происходить.

У меня всё сработало! Если вы всё ещё сталкиваетесь с этой проблемой (или для любого другого, кто найдёт эту тему :sweat_smile:), я думаю, что эта ошибка возникает, если UserEmail.find_by(email: "oid@example.com") ничего не возвращает. Возможно, стоит дважды проверить, точно ли совпадает адрес электронной почты.