How to Properly Send Multilanguage Emails in Kirby

Hi everyone,

I’m having trouble with multilingual emails in Kirby. My site supports multiple languages and I have all my translation keys set up in /site/languages/en.php, /de.php, etc.

When I send an email to a user, I want the email content (subject, table headers, etc.) to be in the user’s language. The user’s language is stored in their account (e.g. 'language' => 'de').

What I do:

Before sending the email, I set the language like this:

$oldLanguage = $kirby->language();
if ($user && $user->language()) {
  $kirby->setCurrentLanguage($user->language());
}

// Collect all data for the email (subject, body, etc.)
// and send the email using translation keys

$kirby->email([
    'from'     => 'noreply@example.com',
    'fromName' => 'My Site',
    'to'       => $user->email(),
    'subject'  => t('order.confirmation.subject'),
    'template' => 'order_confirmation',
    'data'     => [
        'name'     => $user->name(),
        'order_id' => $orderId,
        'products' => $products,
        'total'    => $total,
        // ... other data ...
    ]
]);

if ($oldLanguage) {
  $kirby->setCurrentLanguage($oldLanguage->code());
}

The problem:

Even after setting the language, the translations inside the email (using t('...') in the email template) always use the default language (English), not the user’s language.

Questions:

  • Why does Kirby still use the default language for translations inside the email, even after calling $kirby->setCurrentLanguage($user->language())?

  • Is there a correct way to force Kirby to use the user’s language for all translations when rendering email templates?

  • Is there something else I need to do to make sure the email content is always in the right language?

Any advice or examples would be greatly appreciated!

What you could do is pass the user language in the data array, and then pass that language to each t() helper.

t('mykey', null, $langCode)

Don’t know if there is another or better way.

Try setCurrentTranslation() - either in addition or instead setCurrentLanguage(), not so sure.

I think that might solve it.

1 Like

It sets the I18n::$locale which is used by the t() helper, so that sounds good.