我需要就以下案例提出一些建议:
我已经配置了config / web.php文件,如下所示
'components' => [
...
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'myusername',
'password' => 'mypassword',
'port' => '587',
'encryption' => 'tls',
],
],
同样在控制器中:
$message = Swift_Message::newInstance()
->setSubject('...')
->setFrom(['mymail'])
->setTo(['recipient'])
->setBody('......');
$transport = Swift_SmtpTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
我收到错误:'无法与主机建立连接'(Swift_TransportException)
有什么想法吗?谢谢。
答案 0 :(得分:0)
由于您已将此配置为Yii组件,因此请正确使用它 请参阅documentation示例:
Yii::$app->mailer->compose('contact/html', ['contactForm' => $form])
->setFrom('from@domain.com')
->setTo($form->email)
->setSubject($form->subject)
->send();
另外:见this SO question。
答案 1 :(得分:0)
在您的配置中将其设置为
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'yourusername',
'password' => 'yourpassword',
'port' => '587',
'encryption' => 'tls',
]
],
在您的控制器中,您可以撰写电子邮件。
Yii::$app->mailer->compose('@app/mail/layouts/reset',['model' =>$model])
->setTo('to@example.com')
->setFrom('from@example.com')
->setSubject('Subject Here')
->setTextBody('You can either render the layout or declare your body here')
->send();
在上面的代码中,我使用的是布局。您可以使用布局并将变量传递给布局并使用它们。如果你不想使用效果良好的布局,只需调用compose方法
的Yii :: $ APP-> mailer->组成()
答案 2 :(得分:0)
我做了以下工作并且工作了:
$transport = Swift_SmtpTransport::newInstance(Yii::$app->components['mailer']['transport']['host'], Yii::$app->components['mailer']['transport']['port']);
$transport->setUsername(Yii::$app->components['mailer']['transport']['username']);
$transport->setPassword(Yii::$app->components['mailer']['transport']['password']);