我试图在yii2 Advanced中配置SwiftMailer。我阅读了教程,并在此处使用代码,但是我仍然有一个错误。
就我而言,宾客必须在下载电子书之前提交他的姓名和电子邮件。然后,他们将从我的办公室收到一封电子邮件,其中包含电子书下载链接。
我在common/config/main-local.php
'components' => [
'mailer' => [
'class' => 'yiiswiftmailerMailer',
'viewPath' => '@common/mail',
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'myaccount@gmail.com',
'password' => 'password',
'port' => '465',
'encryption' => 'ssl',
],
],
],
在我的controller/GuestController.php
public function actionCreate()
{
$model = new guest();
if($model->load(Yii::$app->request->post())){
return Yii::$app->mailer->compose()
->setFrom('myaccount@gmail.com')
->setTo($model->email)
->setSubject('halo')
->setTextBody('body')
->send();
$model->save();
return $this->redirect(['buku/index']);
}
else{
return $this->renderAjax('create',[
'model' => $model,
]);
}
}
形式宾客
<div class="guest-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'nama')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>
<?php
echo Alert::widget([
'options' => [
'class' => 'alert-warning',
],
'body' => '[Alert] Check your email for Download',
]);
?>
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
和我的错误,
Swift_transportException连接无法与主机建立 smtp.gmail.com [#0]
我该如何解决?谢谢,它已解决
我始终使用 encryption
的设置为 tls
和port 587
,而您不需要设置 'useFileTransport' => false,
,因为它默认为false to false,请参见 here
>
'mailer' => [
'class' => 'yiiswiftmailerMailer' ,
'viewPath' => '@common/mail',
'transport' => [
'class' => 'Swift_SmtpTransport' ,
'host' => 'smtp.gmail.com' ,
'username' => 'myaccount@gmail.com',
'password' => 'password',
'port' => '587' ,
'encryption' => 'tls' ,
] ,
] ,