SwiftMailer 的 setFrom 不适用于变量

SwiftMailer 's setFrom not working with variable

我正在尝试通过 swiftmailer 和 gmail 在本地发送联系表单的邮件。我检查了每一行,我知道问题是 '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);
    }

});

如你所见,我也使用了 Slim 3 框架。当我 运行 代码时出现此错误:

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

但是如果我用 'x@y.z' 替换 $cleanEmail 代码就可以了! 我应该怎么办? 我知道通过使用 gmail 我无法更改发件人姓名,但我想将此代码上传到虚拟主机中,我不想在那里遇到这个问题。

谁能建议在 Slim 3 中进行重定向的更好方法?而不是这两行:

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

我已经为我的路线设置了这样的名称:

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

非常感谢!

您可能想改为执行以下操作。

$cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
$cleanMsg   = filter_var($msg,FILTER_SANITIZE_STRING);