8 – Receiving error when trying to send email programmatically via custom module

I was wondering if anybody could help, i’m trying to send an email programmatically from a custom module i’ve created, from all the tutorials i’ve seen I think i’m doing some of it correctly however when I run the code I get an error that I really don’t understand.

Below is what I have inside my .module file and below that is the error its giving me.

Absolutely any help would be great.

Thank you.


function modulename_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message('langcode'),
  switch ($key) {
    case 'general_mail':
      $message('from') = Drupal::config('system.site')->get('mail');
      $message('subject') = t('General mail: @subject', ('@subject' => $params('subject')), $options);
      $message('body')() = $params('message');

$mailManager = Drupal::service('plugin.manager.mail');
$module = 'modulename';
$key = 'general_mail';
$to = "mail@mail.com";
$params('message') = "This is the message";
$params('subject') = "Mail subject";
$langcode = Drupal::currentUser()->getPreferredLangcode();
$send = true;

$mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);


TypeError: Argument 1 passed to DrupalCoreRoutingCurrentRouteMatch::getRouteMatch() must be an instance of SymfonyComponentHttpFoundationRequest, null given, called in /var/www/html/web/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on line 127 in /var/www/html/web/core/lib/Drupal/Core/Routing/CurrentRouteMatch.php on line 99