Score:4

How can you attach a file to a mail using Symfony mailer?

ml flag

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 ?

miststudent2011 avatar
fr flag
Seems it can be handled by patch from this issue https://www.drupal.org/project/symfony_mailer/issues/3261807
Score:0
ua flag

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()
];
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.