How to programmatically alter destination email address
Last updated on
10 May 2023
This documentation needs work. See "Help improve this page" in the sidebar.
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
To use the new plugin, click the '+ Add handler' button on the 'Emails/Handlers' page and select 'Local email'.
<?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;
return parent::sendMessage($webform_submission, $message);
}
}
To override the default webform email handler, change the plugin id in the annotation above from "local_email" to "email" and add the following hook implementation to your module:
function my_module_webform_handler_info_alter(array &$handlers) {
$handlers['email']['class'] = Drupal\my_module\Plugin\WebformHandler\MyEmailWebformHandler::class;
}Help improve this page
Page status: Needs work
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion