Search code examples
phpformssymfonyswiftmailer

How to convert UploadedFile object to Swift_Mime_MimeEntity


I have a Symfony 3.3 contact form that sends an email. Now I am trying to add an attachment to the form. I insert the following line in my sendEmail function:

        ->attach($data["attachment"])

... and I get the following error:

Argument 1 passed to Swift_Mime_SimpleMessage::attach() must implement interface Swift_Mime_MimeEntity, instance of Symfony\Component\HttpFoundation\File\UploadedFile given

So my question is: How do I convert my UploadedFile object into something that SwiftMailer will be happy with?

====

Edit #1: I tried this with no success:

$fullFilePath = $data["attachment"]->getPath() . '/' . $data["attachment"]->getClientOriginalName();
$attachment = \Swift_Attachment::fromPath($fullFilePath);

Attaching that "attachment" just resulted in the email not being sent, though the application acted as if it had sent the form.

====

Edit #2: Progress! I'm now able to get a useful error. This code ...

        $extension = $data["attachment"]->guessExtension();
    if($extension !== 'rtf'){
        die('Please give us an rtf file. TODO: Put a better message here!');
    }
    $newFilePath = '/tmp';
    $newFileName = 'temporary.rtf';
    $data["attachment"]->move($newFilePath, $newFileName);

... gives me an error like this:

Could not move the file "/tmp/phpnIqXDr" to "/tmp/temporary.rtf" ()

... which is very frustrating, since I know that /tmp is writeable by every user.


Solution

  • You don't need to move the file, Symfony\Component\HttpFoundation\File\UploadedFile class returns the path and has methods to get the filename and mimetype.

    This code works for me:

    $message->attach(
        \Swift_Attachment::fromPath($data["attachment"])
            ->setFilename(
                $data["attachment"]->getClientOriginalName()
            )
            ->setContentType(
                $data["attachment"]->getClientMimeType()
            )
    );
    

    Credit to toolpixx