swiftmailer and email form with attachment - beginner

Another way to do this, using only a single variable for path and filename is:

$message->attach(Swift_Attachment::fromPath('full-path-with-attachment-name'));

There's a simple way to do this, here you go:

$message->attach(
Swift_Attachment::fromPath('/path/to/image.jpg')->setFilename('myfilename.jpg')
);

That's one way SwiftMail can do this, now just the /tmp file, and turn the above into the following:

Assuming: fileatt is the variable for the $_FILE, ['tmp_name'] actually is the tmp file that PHP creates from the form upload.

$message->attach(
Swift_Attachment::fromPath($_FILES['fileatt']['tmp_name'])->setFilename($_FILES['fileatt']['name'])
);

More information on SwiftMail Attachments can be found on this docs page

More information on $_FILES can be found here on w3schools, despite I don't like w3schools, this page is solid.


Single Attachment

My answer is similar to that of André Catita. However, in Laravel 6 you can use $request instead of $_FILES. Let me simplify the code above:

$path = $request->file('import')->getPathName();
$fileName = $request->file('import')->getClientOriginalName();      

$message->attach(
        Swift_Attachment::fromPath($path)->setFilename($fileName)
        );

Here I assume that the name of your file tag is import. For eg: <input type="file" name="import" />

Multiple Attachments

Now, lets say instead of single attachment you need multiple attachments. Then the code needs to be changed.

First your html code will become: <input type="file" name="import[]" multiple />

And for backend or laravel; code will be:

$files = $request->file('import');
foreach($files as $file){

        $path = $file->getPathName();
        $fileName = $file->getClientOriginalName();      

        $message->attach(
            Swift_Attachment::fromPath($path)->setFilename($fileName)
            );
}