如何在Silex中处理Swift_TransportException

时间:2013-07-22 16:49:59

标签: php swiftmailer silex

我在Silex中捕获SwiftMailer的异常时遇到了一些奇怪的问题。我想发送一封这样的电子邮件:

try {
    $message = \Swift_Message::newInstance()
        ->setSubject('subject')
        ->setFrom(array('form'))
        ->setTo(array('to'))
        ->setBody('body');
    $app['mailer']->send($message);
} catch (\Swift_TransportException $e) {
    $app['logger']->addError('Unable to send welcome email');
}

我知道它不会在localhost上发送任何电子邮件,我希望它会失败,但为什么我无法在Swift_TransportException块中发现try - catch例外?

它只是打印:

Fatal error: Uncaught exception 'Swift_TransportException' with message 'Connection could not be established with host localhost [Connection refused #61]'

2 个答案:

答案 0 :(得分:0)

当您调用send()时,不会立即发送电子邮件,而是在应用程序关闭期间(当响应已经发送时)进入刷新的内存假脱机。这可以改善用户体验,因为响应可以更快地发送。

答案 1 :(得分:0)

我也无法在本地主机上发送邮件 - 我用这段代码摆脱了异常:

/// config
$app['swiftmailer.options'] = array(
    'host' => 'smtp.1und1.de',
    'port' => '465',
    'username' => 'xxx',
    'password' => 'yyy',
    'encryption' => 'ssl',
    'auth' => 'login',
);

// bootstrap
$app->register(new Silex\Provider\SwiftmailerServiceProvider(), array(
    'swiftmailer.options' => $app['swiftmailer.options']
));