0

I'm trying to send mail for a contact form locally by swiftmailer and gmail. I've checked every line and I know the problem is 'setFrom' .

$app->post('/contact', function ($request, $response, $args){
$body = $this->request->getParsedBody();

$name = $body['name'];
$email = $body['email'];
$msg = $body['msg'];

if(!empty($name) && !empty($email) && !empty($msg) ){
    $cleanName  = filter_var($name,FILTER_SANITIZE_STRING);
    $cleanEmail = filter_var($name,FILTER_SANITIZE_EMAIL);
    $cleanMsg   = filter_var($name,FILTER_SANITIZE_STRING);

}else {
    //redirecting to contact page
}

//sending email

$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
    ->setUsername('xxx@gmail.com')
    ->setPassword('xxx');

$mailer= \Swift_Mailer::newInstance($transporter);

$message = \Swift_Message::newInstance();

$message->setSubject('Email from our website');
$message->setTo(array('ns.falahian@gmail.com'));
$message->setBody($cleanMsg);
$message->setFrom([
    $cleanEmail => $cleanName
]);

$result=$mailer->send($message);

    if ($result > 0) {
        $path = $this->get('router')->pathFor('home');
        return $response->withRedirect($path);
    } else {
        $path = $this->get('router')->pathFor('contact');
        return $response->withRedirect($path);
    }

});

as you can see I also use Slim 3 framework. when I run the code I get this error:

Slim Application Error A website error has occurred. Sorry for the temporary inconvenience.

But if I replace the $cleanEmail with 'x@y.z' the code works! what should I do? I know that by using gmail I can't change the sender name but I want to upload this code in a webhost and I don't want to get this issue there.

And can anyone suggest a better way for redirecting in Slim 3? Instead of these two lines:

$path = $this->get('router')->pathFor('contact');
        return $response->withRedirect($path);

I've set names for my routes like this:

$app->get('/contact', function ($req, $res, $args) {
     return $this->view->render($res, "contact.twig");
})->setName('contact');

thanks a lot!

Niloofar
  • 117
  • 1
  • 1
  • 13

1 Answers1

1

You probably want to do the following instead.

$cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
$cleanMsg   = filter_var($msg,FILTER_SANITIZE_STRING);
Mika Tuupola
  • 19,877
  • 5
  • 42
  • 49