mail example

    $this->assertInstanceOf(TestMailCollector::class$mail_backend);
  }

  /** * Assert that the pluggable mail system is functional. */
  public function testErrorMessageDisplay() {
    // Switch mail backends.     $this->configureDefaultMailInterface('test_php_mail_failure');

    // Test with errors displayed to users.     \Drupal::service('plugin.manager.mail')->mail('default', 'default', 'test@example.com', 'en');
    $messages = \Drupal::messenger()->messagesByType(MessengerInterface::TYPE_ERROR);
    $this->assertEquals('Unable to send email. Contact the site administrator if the problem persists.', $messages[0]);
    \Drupal::messenger()->deleteAll();

    // Test without errors displayed to users.     \Drupal::service('plugin.manager.mail')->mail('default', 'default', 'test@example.com', 'en', ['_error_message' => '']);
    $this->assertEmpty(\Drupal::messenger()->messagesByType(MessengerInterface::TYPE_ERROR));
  }

  /** * Tests that message sending may be canceled. * * @see mail_cancel_test_mail_alter() */
 else {
            $subject = $this->encodeHeader($this->secureHeader($subject));
        }
        //Calling mail() with null params breaks         $this->edebug('Sending with mail()');
        $this->edebug('Sendmail path: ' . ini_get('sendmail_path'));
        $this->edebug("Envelope sender: {$this->Sender}");
        $this->edebug("To: {$to}");
        $this->edebug("Subject: {$subject}");
        $this->edebug("Headers: {$header}");
        if (!$this->UseSendmailOptions || null === $params) {
            $result = @mail($to$subject$body$header);
        } else {
            $this->edebug("Additional params: {$params}");
            $result = @mail($to$subject$body$header$params);
        }
        $this->edebug('Result: ' . ($result ? 'true' : 'false'));
        return $result;
    }

    /** * Output debugging info via a user-defined method. * Only generates output if debug output is enabled. * * @see PHPMailer::$Debugoutput * @see PHPMailer::$SMTPDebug * * @param string $str */
'headers' => ['Content-type' => 'text/html'],
      'subject' => $subject,
      'to' => 'foobar@example.com',
      'body' => $body,
    ];

    // Before we send the email, drupalGetMails should return an empty array.     $captured_emails = $this->drupalGetMails();
    $this->assertCount(0, $captured_emails, 'The captured emails queue is empty.');

    // Send the email.     \Drupal::service('plugin.manager.mail')->getInstance(['module' => 'test', 'key' => 'drupal_mail_test'])->mail($message);

    // Ensure that there is one email in the captured emails array.     $captured_emails = $this->drupalGetMails();
    $this->assertCount(1, $captured_emails, 'One email was captured.');

    // Assert that the email was sent by iterating over the message properties     // and ensuring that they are captured intact.     foreach ($message as $field => $value) {
      $this->assertMail($field$valuenew FormattableMarkup('The email was sent and the value for property @field is intact.', ['@field' => $field]));
    }

    
'subject' => $subject,
      'to' => 'foobar@example.com',
      'body' => $body,
    ];

    // Before we send the email, \Drupal\Core\Test\AssertMailTrait::getMails()     // should return an empty array.     $captured_emails = $this->getMails();
    $this->assertCount(0, $captured_emails, 'The captured emails queue is empty.');

    // Send the email.     $mail_service->getInstance(['module' => 'simpletest', 'key' => 'drupal_mail_test'])->mail($message);

    // Ensure that there is one email in the captured emails array.     $captured_emails = $this->getMails();
    $this->assertCount(1, $captured_emails, 'One email was captured.');

    // Asserts that the message fields have the pattern in it.     $this->assertMailPattern('id', $message['id']);
    $this->assertMailPattern('subject', "^.{64}$");
    $this->assertMailPattern('to', "[a-z]{6}@example\.com$");
    $this->assertMailPattern('body', "^.{128}$");

    

    public function _sendMail()
    {
        if ($this->parameters === null) {
            set_error_handler(array($this, '_handleMailErrors'));
            $result = mail(
                $this->recipients,
                $this->_mail->getSubject(),
                $this->body,
                $this->header);
            restore_error_handler();
        } else {
            if(!is_string($this->parameters)) {
                /** * @see Zend_Mail_Transport_Exception * * Exception is thrown here because * $parameters is a public property */

  protected function doMail(string $to, string $subject, string $message, array|string $additional_headers = [], string $additional_params = ''): bool {
    return @mail(
      $to,
      $subject,
      $message,
      $additional_headers,
      $additional_params
    );
  }

  /** * Disallows potentially unsafe shell characters. * * Functionally similar to PHPMailer::isShellSafe() which resulted from * CVE-2016-10045. Note that escapeshellarg and escapeshellcmd are inadequate * for this purpose. * * @param string $string * The string to be validated. * * @return bool * True if the string is shell-safe. * * @see https://github.com/PHPMailer/PHPMailer/issues/924 * @see https://github.com/PHPMailer/PHPMailer/blob/v5.2.21/class.phpmailer.php#L1430 * * @todo Rename to ::isShellSafe() and/or discuss whether this is the correct * location for this helper. */
      if (empty($message['send'])) {
        $message['result'] = NULL;
      }
      // Sending was originally requested and was not canceled.       else {
        // Ensure that subject is plain text. By default translated and         // formatted strings are prepared for the HTML context and email         // subjects are plain strings.         if ($message['subject']) {
          $message['subject'] = PlainTextOutput::renderFromHtml($message['subject']);
        }
        $message['result'] = $system->mail($message);
        // Log errors.         if (!$message['result']) {
          $this->loggerFactory->get('mail')
            ->error('Error sending email (from %from to %to with reply-to %reply).', [
              '%from' => $message['from'],
              '%to' => $message['to'],
              '%reply' => $message['reply-to'] ? $message['reply-to'] : $this->t('not set'),
            ]);
          $error_message = $params['_error_message'] ?? $this->t('Unable to send email. Contact the site administrator if the problem persists.');
          if ($error_message) {
            $this->messenger()->addError($error_message);
          }
Zend_Loader::loadClass($connectionClass);
            }
            $this->setConnection(new $connectionClass($this->_host, $this->_port, $this->_config));
            $this->_connection->connect();
            $this->_connection->helo($this->_name);
        } else {
            // Reset connection to ensure reliable transaction             $this->_connection->rset();
        }

        // Set sender email address         $this->_connection->mail($this->_mail->getReturnPath());

        // Set recipient forward paths         foreach ($this->_mail->getRecipients() as $recipient) {
            $this->_connection->rcpt($recipient);
        }

        // Issue DATA command to client         $this->_connection->data($this->header . Zend_Mime::LINEEND . $this->body);
    }

    /** * Format and fix headers * * Some SMTP servers do not strip BCC headers. Most clients do it themselves as do we. * * @access protected * @param array $headers * @return void * @throws Zend_Transport_Exception */
'default' => 'php_mail',
      'example_testkey' => 'test_mail_collector',
    ];
    $this->setUpMailManager($interface);

    $this->renderer->expects($this->exactly(1))
      ->method('executeInRenderContext')
      ->willReturnCallback(function DRenderContext $render_context$callback) {
        $message = $callback();
        $this->assertEquals('example', $message['module']);
      });
    $this->mailManager->mail('example', 'key', 'to@example.org', 'en');
  }

}

/** * Provides a testing version of MailManager with an empty constructor. */
class TestMailManager extends MailManager {

  /** * Sets the discovery for the manager. * * @param \Drupal\Component\Plugin\Discovery\DiscoveryInterface $discovery * The discovery object. */
    // language.     $recipient_accounts = $this->storage->loadByProperties(['mail' => $recipient]);
    $recipient_account = reset($recipient_accounts);
    if ($recipient_account) {
      $langcode = $recipient_account->getPreferredLangcode();
    }
    else {
      $langcode = $this->languageManager->getDefaultLanguage()->getId();
    }
    $params = ['context' => $this->configuration];

    $message = $this->mailManager->mail('system', 'action_send_email', $recipient$langcode$params);
    // Error logging is handled by \Drupal\Core\Mail\MailManager::mail().     if ($message['result']) {
      $this->logger->notice('Sent email to %recipient', ['%recipient' => $recipient]);
    }
  }

  /** * {@inheritdoc} */
  public function defaultConfiguration() {
    return [
      

    protected function sendWithMail()
    {
        $recipients = is_array($this->recipients) ? implode(', ', $this->recipients) : $this->recipients;

        // _validate_email_for_shell() below accepts by reference,         // so this needs to be assigned to a variable         $from = $this->cleanEmail($this->headers['Return-Path']);

        if ($this->validateEmailForShell($from)) {
            return mail($recipients$this->subject, $this->finalBody, $this->headerStr);
        }

        // most documentation of sendmail using the "-f" flag lacks a space after it, however         // we've encountered servers that seem to require it to be in place.         return mail($recipients$this->subject, $this->finalBody, $this->headerStr, '-f ' . $from);
    }

    /** * Send using Sendmail * * @return bool */
// Set preferred_langcode to 'zh-hant'.     $user = $this->createUser();
    $user->set('preferred_langcode', 'zh-hant')->save();
    $preferredLangcode = $user->getPreferredLangcode();
    $this->assertSame('zh-hant', $preferredLangcode);

    // Recovery email should respect user preferred langcode by default if     // langcode not set.     $this->config('system.site')->set('mail', 'test@example.com')->save();
    $params['account'] = $user;
    $default_email = \Drupal::service('plugin.manager.mail')->mail('user', 'password_reset', $user->getEmail()$preferredLangcode$params);
    $this->assertTrue($default_email['result']);

    // Assert for zh.     $this->assertMailString('subject', 'hant subject', 1);
    $this->assertMailString('body', 'hant body', 1);
    $this->assertMailString('body', 'zh/user/reset', 1);

    // Recovery email should be fr when langcode specified.     $french_email = \Drupal::service('plugin.manager.mail')->mail('user', 'password_reset', $user->getEmail(), 'fr', $params);
    $this->assertTrue($french_email['result']);

    
// Send to the user in the user's preferred language.       $to = $recipient->getEmail();
      $recipient_langcode = $recipient->getPreferredLangcode();
      $params['recipient'] = $recipient;
    }
    else {
      throw new MailHandlerException('Unable to determine message recipient');
    }

    // Send email to the recipient(s).     $key_prefix = $message->isPersonal() ? 'user' : 'page';
    $this->mailManager->mail('contact', $key_prefix . '_mail', $to$recipient_langcode$params$sender_cloned->getEmail());

    // If requested, send a copy to the user, using the current language.     if ($message->copySender()) {
      $this->mailManager->mail('contact', $key_prefix . '_copy', $sender_cloned->getEmail()$current_langcode$params$sender_cloned->getEmail());
    }

    // If configured, send an auto-reply, using the current language.     if (!$message->isPersonal() && $contact_form->getReply()) {
      // User contact forms do not support an auto-reply message, so this       // message always originates from the site.       if (!$sender_cloned->getEmail()) {
        
$expected_headers .= "Reply-to: from@example.org$line_end";

    $mailer->expects($this->once())->method('doMail')
      ->with(
        $this->equalTo('to@example.org'),
        $this->equalTo("=?utf-8?Q?test?={$line_end} =?utf-8?Q?subject?="),
        $this->equalTo(''),
        $this->stringStartsWith($expected_headers),
      )
      ->willReturn(TRUE);

    $this->assertTrue($mailer->mail($message));
  }

}
Home | Imprint | This part of the site doesn't use cookies.