1

I'm on a D9 Site. I've created a module, where I define a hook_mail, a hook_theme and a preprocess for swiftmailer twig:

function my_project_breakout_rooms_theme() {
  return [
    'my_project_breakout_room_email_invite' => [
      'variables' => [
        'brand_name' => NULL,
        'brand_message' => NULL,
        'date' => NULL,
        'start_date' => NULL,
        'end_date' => NULL,
        'mail_to' => NULL,
      ],
    ],
  ];
}

/**
 * Implements hook_mail().
 */
function my_project_breakout_rooms_mail($key, &$message, $params) {
  $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
  $message['from'] = $params['from'];
  $message['subject'] = $params['subject'];
  $message['breakout_room_title'] = $params['breakout_room_title'];
  $message['breakout_room_body'] = $params['breakout_room_body'];
}

function my_project_breakout_rooms_preprocess_swiftmailer__my_project_breakout_rooms__my_project_breakout_rooms_mail(array &$variables) {
  $variables['breakout_room_body'] = $variables["message"]["breakout_room_body"];
  $variables['breakout_room_title'] = $variables["message"]["breakout_room_title"];
}

In a custom rest resource then I send the mail:

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\rest\ResourceResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;

public function post($data) {
  $params['from'] = $this->configFactory->get('system.site')->get('mail');
  $params['brand_message'] = $data["brand_message"];
  $params['subject'] = $data['br_topic'] . ' - ' . t('Appointment confirmation');
  $params['breakout_room_title'] = t($data['br_topic']);
  $params['breakout_room_body'] = $this->getBreakoutRoomBody($data);

  foreach ($data["mail_to"] as $user_mail) {
    $params["breakout_room_body"]['#mail_to'] = $user_mail;
    $result = $this->mailManager->mail('my_project_breakout_rooms', 'my_project_breakout_rooms_mail', $user_mail, $this->getUserLanguage($user_mail), $params, NULL, TRUE);
    if (!$result['result']) {
      throw new HttpException(400, 'Impossibile inviare email');
    }
  }
  return new ResourceResponse(['email_sent' => TRUE]);
}

private function getUserLanguage($user_mail) {
  $user = user_load_by_mail($user_mail);
  return $user ? $user->getPreferredLangcode() : 'it';
}

private function getBreakoutRoomBody($data) {
  $body = [
    '#brand_name' => $data['brand_name'],
    '#brand_message' => $data['brand_message'],
    '#date' => $this->formateDate($data['br_date'], 'd/m/Y'),
    '#start_date' => $this->formateDate($data['br_start'], 'H:i'),
    '#end_date' => $this->formateDate($data['br_end'], 'H:i'),
  ];
  
  $body['#theme'] = 'my_project_breakout_room_email_invite';
  return $body;
}

private function formateDate($date, $format) {
  $date = new DrupalDateTime($date, 'UTC');
  $date->setTimezone(new DateTimeZone($this->timezone));
  return $date->format($format);
}

Then in the swiftmail swiftmailer--my-project-breakout-rooms--my-project-breakout-rooms-mail.html.twig twig I print the title\body variables.

{% embed "@mytheme/mail/swiftmailer.html.twig" %}
    {% block mail_body %}
        <table border="0" cellpadding="0" cellspacing="0" width="600" class="breakout-room-body">
            <tr class="left-text">
                <td>
                    {{ breakout_room_title }}
                    {{ breakout_room_body }}
                </td>
            </tr>
        </table>
    {% endblock %}
{% endembed %}

The twig of my-project-breakout-room-email-invite.html.twig is

<div class="breakout-room-email-body">
    <p>
        {{ 'Hello'|t }},
    </p>
    <p>
        {% trans %}
            You are invited to the appoinment with Brand {{ brand_name }} on {{ date }} from {{ start_date }}
            to {{ end_date }}
        {% endtrans %}
    </p>
    <p>
        {{ brand_message }}
    </p>

    <table class="outer-table-link-wrapper">
        <tr class="text left-text" height="40">
            <td colspan="6">
                <table class="button-link" cellpadding="0" cellmargin="0" border="0" height="44" width="200">
                    <tr>
                        <td bgcolor="#E30613" valign="middle" align="center" width="200">
                            <div class="div-wrapper">
                                <a href="{{ drupal_url('/breakout', {absolute: true, query: {mail: mail_to}}) }}">
                                    {{ 'Reply'|t }}
                                </a>
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
    <p>{{ 'If you are not yet registered, please consider signin up before responding to the Brand\'s invitation'|t }}</p>
    <table class="outer-table-link-wrapper">
        <tr class="text left-text" height="40">
            <td colspan="6">
                <table class="button-link" cellpadding="0" cellmargin="0" border="0" height="44" width="200">
                    <tr>
                        <td bgcolor="#E30613" valign="middle" align="center" width="200">
                            <div class="div-wrapper">
                                <a href="{{ url('simplesamlphp_auth.saml_login') }}">
                                    {{ 'Sign Up'|t }}
                                </a>
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</div>

The email is successfully send, but I can't find a way to send the translated version of that, the email are always send in Italian - the site has Italian as default language and English as other.

I've already found some questions on the argument, but they couldn't solve my problem: trying to use the ConfigOverrideLanguage orrenderRoot or both don't change anything for me.

5
  • github.com/Niklan/niklan.net-examples/tree/master/blog/214/… see sample how to send in preferred Language.
    – Nikit
    May 12, 2021 at 22:10
  • @Nikit what you do in MailHandler.php is similar to what I've tried before, but just to be sure I've tried your exact code in my project and it doesn't work, mails are always send in Italian (if the string translation exists). I've edited my question to specify I'm on D9, dunno if this can be the cause.
    – Giuseppe
    May 13, 2021 at 8:57
  • It might be more clear if you simplified your code, because right now it's not clear that you're doing what you think you're doing. For example, 'my_module_mail' is used in at least three separate and distinct ways: 1) As the name of a hook_mail() implmentation, 2) As the name of a theme hook, and 3) As a mail key.And how does the contents of $params['my_mail_body'] get rendered? Normally any element of $params[] that does not have a 'known' key gets ignored. An unknown key like 'my_module_body' isn't used unless your hook_mail() makes use of it.
    – anonymous
    May 13, 2021 at 20:36
  • 1
    Likewise, do you really know that $this->getUserLanguage($user_mail) passes the correct value to mail()?
    – anonymous
    May 13, 2021 at 20:42
  • @anonymous I had to hide some sensible information, but I agree the code was not most clear. I've updated the answer, I hope someone can help me. One thing I'm going to try as soon as I've time is to check if is the fact I'm "printing" a renderable array inside another that cause the problem
    – Giuseppe
    Jun 25, 2021 at 9:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.