Hello community

How can I send an e-mail in the user's language?

I have this code:

function _custom_function_create_body(){
  $emailadress = 'test@test.com';
  $subject= t('This subject should be translatable');
  $account = $user_account;
  $body_message = t('This text should be translatable');
  _custom_function_email_send($emailadress, $subject, $body_message,$account);
}

function _custom_function_email_send($emailadress, $subject, $body_message, $account) {
  $message = array(
    'key' => 'my_custom_key',
    'from' => 'test@test.com',
    'module' => 'my_module',
    'to' => $emailadress,
    'subject' => $subject,
    'body' => $body_message,
    'language' => user_preferred_language($account), // this line not working
    'headers' => array(
      'Content-Type' => 'text/html; charset=UTF-8;'),   //needed
    'plain' => NULL,
    'plaintext' => NULL,
  );

  $mime_mail_system = drupal_mail_system('mimemail', 'my_custom_key');
  $message = $mime_mail_system->format($message);
  if ($mime_mail_system->mail($message)) {
    // drupal_set_message('Sent.');
  }
  else{
    // drupal_set_message('Fail.', 'error');
  }
}

The email is sent, but not in the correct translation. The body and subject text shows in the email always in the default site language.

How i send the body and subject text in the user account language?

Comments

sgabe’s picture

You can try the global language variable.

Anonymous’s picture

Status: Active » Closed (works as designed)

Ok i find the solution :)

In the drupal system mail settings i defined for all e-Mails the Mime Mail class. After that i activated the module «Mime Mail CSS Compressor». So i can send HTML e-mails with MIME-Mail with the drupal function drupal_mail();

And in the drupal_mail() function i can set the user_preferred_language().

Afer that, i implement the hook_mail() function and my message to the parameter $message['body'][]. In this t('...') string, i define the language parameter array('langcode' => $message['language']->language).

Et voilà, e-mails are sent in html with mime-mail and the correct user language.

Anonymous’s picture

Assigned: » Unassigned