I have create a form that upload a file.
This file is send as email attachment
..
$form['cv'] = [
'#type' => 'managed_file',
'#title' => 'Votre CV',
'#required' => true,
'#upload_validators' => [
'file_validate_extensions' => ['pdf doc docx odt odf'],
'file_validate_size' => 4000,
],
];
..
on form submit
..
$cv_id = $form_state->getValue('cv')[0];
$cv_entity = File::load($cv_id);
$attachments = [
$cv_entity,
];
..
$result = $this->mailManager->mail($module, $key, $to, $language_code, $params, $reply, $send);
if ($result['result'] == true) {
$this->messenger()
->addMessage('Your application has been sent.');
..
function hook_mail($key, &$message, $params) {
$options = [
'langcode' => $message['langcode'],
];
switch ($key) {
// Send a simple message from the contact form.
case 'beetween_postulate':
$from = \Drupal::config('system.site')->get('name');
$message['subject'] = t('E-mail envoyé depuis le site @site-name', ['@site-name' => $from], $options);
// Note that the message body is an array, not a string.
$params = $message['params'];
$mime_id = md5(uniqid(time() . rand(), 1));
$headers = &$message['headers'];
$message_content_type = $headers['Content-Type'];
$headers['Content-Type'] = "multipart/mixed; boundary=\"$mime_id\"";
$body = "This is a multi-part message in MIME format.\r\n";
$body .= "--$mime_id\r\n";
$body .= "Content-Type: $message_content_type \r\n\r\n";
$body .= $params['body'] . "\r\n\r\n";
if (!empty($params['attachments'])) {
$fs_service = \Drupal::service('file_system');
$fmtg_service = \Drupal::service('file.mime_type.guesser');
foreach ($params['attachments'] as $file) {
// Here we add the attachment to the message body.
$file_name = $fs_service->basename($file);
$mime_type = $fmtg_service->guess($file);
$file_content = file_get_contents($file);
$base64 = chunk_split(base64_encode($file_content));
$body .= "--$mime_id\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Type: $mime_type;
name=$file_name\r\n";
$body .= "Content-Disposition: attachment;
filename=$file_name\r\n\r\n";
$body .= $base64 . "\r\n\r\n";
}
}
$body .= '--' . $mime_id . '--';
$message['body'] = [$body];
break;
}
}
it does work for most case
but it does not work for some file names ,
although the
mailManager->mail
returns true, the email is not sent
for examples:
AMU - Réglement INDEED pour diffusion des offres d'emplois AMU.pdf
CV.dupond.pdf
How can i convert these files names to a correct format / or return a validator error on upload ?
Is this not a bug of the mail->manager method to return true in that case ?