Skip to main content
New tool CRON Expression Builder — preview next run times before you schedule Apex. Open the builder →
Code snippet showing how to use the Apex System.setPassword method for setting Salesforce user passwords quickly
Apex

System.setPassword in Apex: Set a Salesforce User's Password

System.setPassword(userId, password) sets a Salesforce user's password from Apex with no email, which makes it the fastest way to prepare sandbox test users. This reference covers the syntax, the errors, the documented first-login rule, and how it compares with resetPassword, resetPasswordWithEmailTemplate and movePassword.

The short answer

System.setPassword(userId, password) is a static Apex method that sets a Salesforce user's password to the value you pass, with no email and no return value. It throws an exception if the password breaks the org's password policy, and a user with no security question set is sent to the Change Your Password page at first login.

Key takeaways Signature: System.setPassword(ID userId, String password) returns Void and sends no email. A password that breaks the org or profile password policy throws an exception. Per the Apex Reference, a user with no security question set lands on the Change Your Password page the first time they log in with a password set by setPassword(). Brand-new test users usually fall into this group. Run the script in Web Console (Setup > Web Console > Run Apex) or with sf apex run. Since Winter '27, Developer Console is hidden from the Setup menu until you set Enable Developer Console to Active. Use System.resetPassword(userId, true) when the user should get Salesforce's reset email, and resetPasswordWithEmailTemplate for Experience Cloud external users. Keep setPassword in sandboxes and admin-only scripts, never hardcode real passwords, and deactivate test users when the cycle ends.

System.setPassword(userId, password) is a static Apex method that sets a Salesforce user's password to the value you pass. It returns nothing, sends no email, and throws an exception if the password breaks the org's password policy.

System.setPassword(userId, 'NewPassword1!');

I use it to get a batch of sandbox test users ready for a QA cycle without waiting on welcome-email links. The other Apex password methods fit other jobs, and the comparison table further down shows which one to pick.

Syntax

public static Void setPassword(ID userId, String password)
  • userId: the ID of the User whose password you are setting.
  • password: the new password, as plain text.
  • Returns nothing. If the password is rejected, the call throws an exception instead.

A complete anonymous Apex example

Run it as an administrator in a sandbox, either in Web Console (Setup > Web Console > Run Apex), with sf apex run --target-org <alias> --file set-pwd.apex, or in Developer Console. As of Winter '27, Developer Console no longer appears in the Setup menu by default; to bring it back, enter Development in Quick Find, select Web Console and set Enable Developer Console to Active. If you haven't switched yet, my notes on Web Console, the Developer Console successor cover the move.

From a terminal, save the script as set-pwd.apex and run it against the sandbox alias:

sf apex run --target-org uat --file set-pwd.apex

Winter '27 also added a --debug-level flag to sf apex run, which sets the debug log level for that run.

The single-user version:

User u = [SELECT Id FROM User WHERE Username = '[email protected]' LIMIT 1];
System.setPassword(u.Id, 'Uat-Tester-2026!');
System.debug('Password set for ' + u.Id);

For several users at once, loop over a query. Keep the password out of anything you commit. Pass it in at run time or generate one per user and hand it over through a secure channel:

String pwd = 'replace-me-at-run-time';
for (User u : [SELECT Id FROM User WHERE Profile.Name = 'QA Tester' AND IsActive = true]) {
  System.setPassword(u.Id, pwd);
}

The version I keep in a team runbook refuses to run outside a sandbox and gives each tester their own password. IsSandbox on the Organization object is true in every sandbox, so if someone pastes this into production the assertion fails before any password changes:

Organization org = [SELECT IsSandbox FROM Organization LIMIT 1];
Assert.isTrue(org.IsSandbox, 'Stop: this script only runs in a sandbox.');

Map<String, String> pwdByUsername = new Map<String, String>{
    '[email protected]' => 'paste-at-run-time-1',
    '[email protected]' => 'paste-at-run-time-2'
};
for (User tester : [SELECT Id, Username FROM User
                    WHERE Username IN :pwdByUsername.keySet() AND IsActive = true]) {
    System.setPassword(tester.Id, pwdByUsername.get(tester.Username));
    System.debug('Password set for ' + tester.Username);
}

Errors you will hit

  • Password policy: the value must meet the org's policy, which covers minimum length, required character mix and password history. A short or reused password makes the call throw an exception that carries the policy message. Check Setup > Password Policies first. A profile can override the org-wide policy, so check the profile too.
  • Bad user ID: a query that matches no user throws System.QueryException: List has no rows for assignment to SObject before setPassword runs. Check the username, and remember that sandbox usernames carry the sandbox suffix.
  • SSO-only users: if users sign in through SSO and the org has disabled username and password login, a password you set has nowhere to be used. Integration users shouldn't depend on a password set this way either; if any still authenticate with one, move integrations off the OAuth username-password flow.
  • Permissions: the running user needs enough access to manage the target user, which in practice means an admin with Manage Users. The SOAP API setPassword() call needs the same rights. It also can't change your own password unless the Password Policies setting "Allow use of setPassword() API for self-resets" is on. Otherwise use changeOwnPassword(), which is the safer call because it checks the current password first.

What happens at first login

The Apex Reference states the rule: if the user hasn't set up a security question, logging in with a password set by setPassword() sends them to the "Change Your Password" page. A test user created yesterday has never had a chance to pick a security question, so plan for that page on their first login and leave time for it in the QA schedule.

resetPassword always prompts for a new password at login, and also asks for a security question and answer if the user hasn't chosen one. The same reference recommends setPassword when you don't want the user prompted for a new password.

setPassword vs resetPassword vs resetPasswordWithEmailTemplate

System.resetPassword(userId, sendUserEmail) generates a random password, returns a System.ResetPasswordResult, and with true emails the user a login link; the user must choose a new password at next login. I reach for it when a real person needs a reset and keep it out of scripted test setup.

Method Signature / returns Email sent? Prompted for new password at login? Use it when
setPassword setPassword(ID, String) returns Void No Only if no security question is set Sandbox test users, scripted QA setup
resetPassword resetPassword(ID, Boolean) returns System.ResetPasswordResult Only when sendUserEmail is true Yes A real internal user needs a reset
resetPasswordWithEmailTemplate resetPasswordWithEmailTemplate(Id, Boolean, String) returns System.ResetPasswordResult Yes, with the named email template Yes Experience Cloud external users (the email address isn't verified)
movePassword movePassword(ID targetUserId, ID sourceUserId) returns Void No n/a Converting a user to another user type; Salesforce must enable it

resetPassword returns a System.ResetPasswordResult. When you pass false, getPassword() on that result returns the generated password, which is useful in a sandbox where email deliverability is set to System Email Only.

System.ResetPasswordResult result = System.resetPassword(userId, false);
System.debug(result.getPassword());

movePassword covers a narrow case, such as converting an external user into a user type with less restrictive access, and you have to ask Salesforce for access to it. The target user, the source user and the running user must all be in the same org. Neither the target nor the source can be the running user, and a user without a password can't be the source. After the move, the target logs in with the moved password and the source has none, so the source needs a reset before it can log in again.

Is System.setPassword safe in production?

Salesforce's Apex Reference says: "Be careful with this method, and don't expose this functionality to end users." Don't call it from an @AuraEnabled method, a Flow-invocable action or a REST endpoint that a non-admin can reach, because whoever can call that code can take over another user's login. Log every call with the running user, the target user ID and a timestamp, and never log the password itself.

My rule is sandboxes only. Setting known passwords for real people in production weakens security, and an auditor will ask why it happened. Real users get SSO or the standard reset flow. A "temporary" admin utility that calls setPassword tends to stay in production long after the reason for it is gone, and a soql-in-loops-security-review-impact-for-managed-packages/" class="auto-link">security review will treat it as a backdoor. If what you want is to check what a user can see from inside Apex tests, test as another user with System.runAs, which needs no password.

Rules I follow with it

  • No hardcoded passwords in classes, test data factories or CI scripts.
  • Deactivate test users when the testing cycle ends, so a known password does not outlive its purpose.
  • When the goal is giving a tester different access, use a permission set instead of a shared login. Shared credentials make the audit trail useless.

If you are deciding whether to script user setup in Apex or build it in Flow, the trade-offs are in Apex vs Flow.

What to watch for

  • Fresh test users have no security question, so their first login with a set password lands on Change Your Password.
  • A profile-level password policy can be stricter than the org-wide one. Test your chosen value against the strictest profile in the batch.
  • In Web Console, Apex is read-only in production orgs, and running queries needs the Use Any API Client user permission. Do this work in a sandbox.
  • resetPasswordWithEmailTemplate doesn't verify an external user's email address, so confirm the address on the record before you trigger it.

FAQ

What does System.setPassword do in Salesforce?

It sets the password of the user whose ID you pass to the exact value you supply, from Apex. Nothing is emailed, and the call throws an exception if the value breaks the org's password policy.

What is the syntax of System.setPassword() in Apex?

The signature is public static Void setPassword(ID userId, String password). It takes a User ID and a plain-text password and returns nothing.

Does System.setPassword send an email?

No. setPassword never emails the user. If you want Salesforce to send a reset email with a login link, call System.resetPassword(userId, true) instead.

What is the difference between System.setPassword and System.resetPassword?

setPassword applies a password you choose and sends no email. resetPassword generates a random password, returns a System.ResetPasswordResult, emails the user when sendUserEmail is true, and always makes the user choose a new password at next login.

Will the user have to change a password set with System.setPassword?

Only if they have no security question configured. In that case the Apex Reference says they are redirected to the Change Your Password page when they log in with the new password.

Frequently asked questions

What does System.setPassword do in Salesforce?

It sets the password of the user whose ID you pass to the exact value you supply, from Apex. Nothing is emailed, and the call throws an exception if the value breaks the org's password policy.

What is the syntax of System.setPassword() in Apex?

The signature is public static Void setPassword(ID userId, String password). It takes a User ID and a plain-text password and returns nothing.

Does System.setPassword send an email?

No. setPassword never emails the user. If you want Salesforce to send a reset email with a login link, call System.resetPassword(userId, true) instead.

What is the difference between System.setPassword and System.resetPassword?

setPassword applies a password you choose and sends no email. resetPassword generates a random password, returns a System.ResetPasswordResult, emails the user when sendUserEmail is true, and always makes the user choose a new password at next login.

Will the user have to change a password set with System.setPassword?

Only if they have no security question configured. In that case the Apex Reference says they are redirected to the Change Your Password page when they log in with the new password.

Newsletter

One email every Tuesday

New guides, tool updates, and the release-note changes that break things.

No spam. Unsubscribe in one click.

Comments

Loading comments...

Leave a Comment