diff --git a/lib/phpmailer/moodle_phpmailer.php b/lib/phpmailer/moodle_phpmailer.php index eda2afd7d51..d0e29600f9a 100644 --- a/lib/phpmailer/moodle_phpmailer.php +++ b/lib/phpmailer/moodle_phpmailer.php @@ -128,12 +128,17 @@ class moodle_phpmailer extends PHPMailer { protected function PostSend() { // Now ask phpunit if it wants to catch this message. - if (PHPUNIT_TEST && phpunit_util::is_redirecting_messages()) { + if (PHPUNIT_TEST) { + if (!phpunit_util::is_redirecting_phpmailer()) { + debugging('Unit tests must not send real emails! Use $this->start_phpmailer_redirection()'); + return true; + } $mail = new stdClass(); $mail->header = $this->MIMEHeader; $mail->body = $this->MIMEBody; $mail->subject = $this->Subject; $mail->from = $this->From; + $mail->to = $this->to[0][0]; phpunit_util::phpmailer_sent($mail); return true; } else { diff --git a/lib/tests/moodlelib_test.php b/lib/tests/moodlelib_test.php index 63a49363b20..2c6cfc6238c 100644 --- a/lib/tests/moodlelib_test.php +++ b/lib/tests/moodlelib_test.php @@ -2658,4 +2658,36 @@ class moodlelib_testcase extends advanced_testcase { $this->assertFalse(password_is_legacy_hash($user->password)); } } + + public function test_email_to_user() { + $this->resetAfterTest(); + + $user1 = $this->getDataGenerator()->create_user(); + $user2 = $this->getDataGenerator()->create_user(); + + $subject = 'subject'; + $messagetext = 'message text'; + $subject2 = 'subject 2'; + $messagetext2 = 'message text 2'; + + unset_config('noemailever'); + + $sink = $this->redirectEmails(); + email_to_user($user1, $user2, $subject, $messagetext); + email_to_user($user2, $user1, $subject2, $messagetext2); + $this->assertSame(2, $sink->count()); + $result = $sink->get_messages(); + $this->assertCount(2, $result); + $sink->close(); + + $this->assertSame($subject, $result[0]->subject); + $this->assertSame($messagetext, trim($result[0]->body)); + $this->assertSame($user1->email, $result[0]->to); + $this->assertSame($user2->email, $result[0]->from); + + $this->assertSame($subject2, $result[1]->subject); + $this->assertSame($messagetext2, trim($result[1]->body)); + $this->assertSame($user2->email, $result[1]->to); + $this->assertSame($user1->email, $result[1]->from); + } }