5

I want to attach a file to a mail from an input file in my form. Here is how I build the mail :

$mailManager = \Drupal::service('plugin.manager.mail');
$params['title'] = 'title test';
$params['message'] = 'my message example';
$form_file = $form_state->getValue('my_input_file');
if (isset($form_file[0]) && !empty($form_file[0])) {
      $file = File::load($form_file[0]);
      $params['attachments'][] = $file;
}
$to = '[email protected]';
$result = $mailManager->mail('my_module', 'my_key', $to, \Drupal::currentUser()->getPreferredLangcode(), $params, NULL, TRUE);

I'm also using an EmailBuilder for rendering the mail :

/**
 * Defines the Email Builder plug-in for my_module module.
 *
 * @EmailBuilder(
 *   id = "my_module",
 *   sub_types = { },
 * )
 */
class DemandeCreationEmailBuilder extends EmailProcessorBase
{

  /**
   * {@inheritdoc}
   */
  public function preRender(EmailInterface $email)
  {
    $email->setSubject($email->getParam('title'));
    $email->setBody(array(
        'site' => \Drupal::config('system.site')->get('name'),
        'message' => $email->getParam('message'),
        'attachments' => $email->getParam('attachments'), // I tried this but it's not working
      )
    );
  }

}

The data from message is correctly included in the mail, but the file is not.

I'm using the Symfony Mailer module (version : 1.0.0-alpha7) to send mails. My version of Drupal is 9.

Does anyone know how to solve this problem please ?

1

1 Answer 1

0

I haven't used that module yet, but I think its

$file = File::load($form_file[0]);
$params['attachments'][] = [
  'filepath' => $file->createFileUrl(FALSE),
  'filename' => $file->getFilename(),
  'filemime' => $file->getMimeType()
];

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.