I'm using the Symfony Mailer package to upload files via email. I'm using PHP 8.2 and v6.2 of symfony/mailer. My form allows users to add a maximum of 4 files for upload. The docs on file attachments show how this can be done statically but I need to add them dynamically by parsing the uploaded $_FILES
array. Not surprisingly this example results in a 500 error because you can't add a loop within a method chain.
<?php
require('lib/composer/vendor/autoload.php');
use Symfony\Component\Mailer\Transport;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\File;
$user = '';
$password = '';
$transport = Transport::fromDsn('smtp://' . $user . ':' . $password . '@domain.co.uk:25');
$mailer = new Mailer($transport);
$email = (new Email())
->from(new Address('from@email.co.uk', 'Name'))
->to('my@email.co.uk')
->subject('Hi this is a test using Symfony Mailer!')
->text('Sending emails is fun again!')
->addPart(new DataPart(new File('test.png'), 'Attached File'))
->html('<p>See Twig integration for better HTML integration!</p>');
// Check for an uploaded file
for($i=0; $i<=3; $i++) {
if(!empty($_FILES['uploaded_file']['tmp_name'][$i])) {
$email->addPart(new DataPart(new File($_FILES['uploaded_file']['tmp_name'][$i]), $_FILES['uploaded_file']['name'][$i]));
}
}
$mailer->send($email);
?>
<form method='post' enctype='multipart/form-data' action=''>
<input class='upload_file' type='file' name='uploaded_file[]' id='upload_file1'>
<input class='upload_file' type='file' name='uploaded_file[]' id='upload_file2'>
<input class='upload_file' type='file' name='uploaded_file[]' id='upload_file3'>
<input class='upload_file' type='file' name='uploaded_file[]' id='upload_file4'>
<input type='submit'>
</form>
See Twig integration for better HTML integration!
');`. So simple typo there. – Will B. Mar 27 '23 at 21:41