How to programmatically alter destination email address based on user input in Drupal 8 Webform

In this article we will see how we could change the destination email address programmatically based on user input.

You can also folow this article from drupal.org to achieve same results. I am also going to follow the same but will elaborate more. So that it will be easy to understand.
 
What do you need to have is one working Drupal 8 custom module. Please follow these guidelines to create one if you do not have already.
 
I assume you have created a custom module, now add a file at following location,
 
my_module/src/Plugin/WebformHandler/MyEmailWebformHandler.php
 
Then copy below code and paste it into that file created. What it will do is, it will create a handler which will be accissible from your webform.
To check your handler, edit webform and click on "Emails / Handlers".
 
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 addr per language."),
 *   cardinality = \Drupal\webform\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\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); } }
Above code snippet shows how you could route emails based on langauge. But what if you would want to consider user submitted data?
Well in that case, you have got the data in $webform_submission variable. 
 
Say if you want tto use the postal code from that array, 
you have to use it as,
 
$user_postal_code = $webform_submission->getData('post_code');
Once this is done, go and clear cache using "drush cr all" and enable the module. 
 
You will find your new handler in webform handlers. To enable your behaviour go and add new handler.
you will see your newly created handler in that list. After you have added it, you will be able to use the webform as per your code's logic.
 
I hope you have found it easy to implement and it helped you achieving your feature. 
 
Please let me know in comments if you face any issues.
 
Thanks!!
Author
No comments available.