How to programmatically alter destination email address

Last updated on
9 July 2017

You can alter the destination (to) address by adding a WebformHandler plugin. You can for example extend the EmailWebformHandler and add your own custom logic. This example changes the recipient based on the site's language:

The location of this file would be my_module/src/Plugin/WebformHandler/MyEmailWebformHandler.php

namespace Drupal\my_module\Plugin\WebformHandler;

use Drupal\webform\Plugin\WebformHandler\EmailWebformHandler;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Emails a webform submission.
 *
 * @WebformHandler(
 *   id = "local_email",
 *   label = @Translation("Local email"),
 *   category = @Translation("Notification"),
 *   description = @Translation("Sends a webform submission to a different email address per language."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 * )
 */
class MyEmailWebformHandler extends EmailWebformHandler {

  public function sendMessage(WebformSubmissionInterface $webform_submission, array $message) {

    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

    switch($language) {

      case 'nl':
        $recipient = 'info@example.nl';
        break;

      case 'ru':
        $recipient = 'info@example.ru';
        break;

      case 'en':
      default:
        $recipient = 'info@example.com';
        break;

    }

    $message['to_mail'] = $recipient;

    parent::sendMessage($webform_submission, $message);
  }

}