Search code examples
symfonysymfony-mailer

Symfony: How to send a file as email-attachment without saving it


I am using symfony 6.1. I have a form that accepts a file upload which works as far as I can see.

The form is not backed by an entity and in this particular case I don't really see the necessity to save the uploaded file somewhere. It would be enough to send it as an attachment of a mail. I read about attaching files using symfony's mailer component but the examples only cover attaching files by paths.

Is it even possible to skip the step to save the file somewhere?


Solution

  • It is possible to add attachments and embed images from streams - so without saving it.

    Attachments

    $email = (new Email())
        // ...
        ->attach(fopen('/path/to/documents/contract.doc', 'r'))
    ;
    

    Embedded images

    $email = (new Email())
        // ...
        // get the image contents from a PHP resource
        ->embed(fopen('/path/to/images/logo.png', 'r'), 'logo')
    ;
    

    You can read more about it in the symfony docs.