diff --git a/core/modules/user/src/AccountForm.php b/core/modules/user/src/AccountForm.php index ecb2a50d75..6c61418097 100644 --- a/core/modules/user/src/AccountForm.php +++ b/core/modules/user/src/AccountForm.php @@ -399,8 +399,10 @@ public function submitForm(array &$form, FormStateInterface $form_state) { $account_cloned = clone $account; $account_cloned->setEmail($new_mail); if (_user_mail_notify('mail_change_verification', $account_cloned) !== NULL) { - // Send notification email to the old email address. - _user_mail_notify('mail_change_notification', $account); + // Send notification email to the old email address, if it's set. + if ($old_mail) { + _user_mail_notify('mail_change_notification', $account); + } // The user's mail address will be updated only after verification. $form_state->setValue('mail', $old_mail); $this->messenger()->addWarning($this->t('Your updated email address needs to be validated. Further instructions have been sent to your new email address.')); diff --git a/core/modules/user/tests/src/Functional/UserMailChangeTest.php b/core/modules/user/tests/src/Functional/UserMailChangeTest.php index bd5d0e6aad..c283864c1d 100644 --- a/core/modules/user/tests/src/Functional/UserMailChangeTest.php +++ b/core/modules/user/tests/src/Functional/UserMailChangeTest.php @@ -99,6 +99,32 @@ public function testMailChange() { self::assertSame(User::load($this->account->id())->getEmail(), $new_mail); } + /** + * Tests email change functionality for a user without E-mail address. + * + * Drupal allows accounts without E-mail when the account is created by an + * administrator. The other way around, changing an non-empty E-mail to an + * empty one, is not allowed. + */ + public function testMailChangeForUserWithEmptyEmail() { + // Simulate a user without an E-mail address. + $this->account->setEmail(NULL)->save(); + + $this->drupalLogin($this->account); + $edit = [ + 'mail' => $this->getRandomEmailAddress(), + 'current_pass' => $this->account->pass_raw, + ]; + $this->drupalPostForm($this->account->toUrl('edit-form'), $edit, 'Save'); + + // Check that the validation status message has been displayed. + $this->assertSession()->pageTextContains('Your updated email address needs to be validated. Further instructions have been sent to your new email address.'); + + // Check that only the verification message was sent. + $this->assertCount(1, $this->getMails()); + $this->assertNotEmpty($this->getMails(['id' => 'user_mail_change_verification'])); + } + /** * Tests email change functionality when E-mail change verification is off. */