I try to implement Symfony Mailer to work with contact form. Everything Ok (user’s name, email, phone, message are sent). But until attempting to send attached file. The contact form doesn’t work (the program hangs).
I tried to find a solution, but failed.
What is going wrong?
Thank you in advance.
<?php
namespace App\Action;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
final class MailerAction
{
private $mailer;
public function __construct(MailerInterface $mailer)
{
$this->mailer = $mailer;
}
public function __invoke(ServerRequestInterface $request,
ResponseInterface $response): ResponseInterface
{
// getting user's inputs (name, email, phone, message,
// file) via AJAX jQuery
$arr = $request->getParsedBody();
// ....
// file attached
$file = $arr["user_file"];
// sanitizing and validating user's inputs
// ....
$messageBody = "<b>Name:</b> ".$name."<br><b>Phone:</b> ".$phone."<br><b>E-mail:</b> ".$email."<br><b>Message:</b> ".$msg;
$mail = new Email();
$mail->from('name@mail.com')
->to('name@mail.com')
->subject('OnLine Order')
->html($messageBody);
// attachment
if (!empty($file['name'][0])) {
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $file['name']));
$filename = $file['name'];
if (move_uploaded_file($file['tmp_name'], $uploadfile)) {
$mail->attachFromPath($uploadfile, $filename);
}else {
$note = array('success' => false, 'message' => 'No file!');
$response->getBody()->write(json_encode($note));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
}
}else {
$note = array('success' => false, 'message' => 'Add file!');
$response->getBody()->write(json_encode($note));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
}
try {
$this->mailer->send($mail);
$note = array('success' => true, 'message' => 'Thank you. Your order has sent.');
$response->getBody()->write(json_encode($note));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
} catch (Exception $exception) {
$note = array('success' => false, 'message' => "Mailer Error!");
$response->getBody()->write(json_encode($note));
return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
}
}
}
It looks like you are sending the file via Ajax so you don’t need move_uploaded_file.
What is the value of $file = $arr["user_file"];?
Does it contain an absolute path from the server? Which would be a security issue.
If you have the file content as string or stream you could alternatively use the attach() method to attach contents from a stream: