我正在尝试通过swift邮件发送电子邮件。我知道有很多相似的问题,但无法理解我的问题在哪里。我这样做就像我在youtube中的教程视频中看到的那样(不知道我会在这里发布链接)但是就像视频一样,但是我的项目没有:DI尝试使用端口465和加密ssl也没有结果。请你一些建议!提前谢谢!
actionContact:
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh();
}
return $this->render('contact', [
'model' => $model,
]);
}
邮件程序配置:
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@app/mail',
// 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.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'tomaivanovtomov@gmail.com',
'password' => 'password',
'port' => '587',
'encryption' => 'tls',
],
],
和params:
return [
'adminEmail' => 'tomaivanovtomov@gmail.com',
];
我对这些电子邮件的熟悉情况还很远,而且我还在学习,所以请不要因为这个可悲的问题而生我的气!:)
修改: ContactForm模型:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* ContactForm is the model behind the contact form.
*/
class ContactForm extends Model
{
public $name;
public $email;
public $title;
public $body;
public $verifyCode;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
// name, email, subject and body are required
[['name', 'email', 'title', 'body'], 'required'],
// email has to be a valid email address
['email', 'email'],
// verifyCode needs to be entered correctly
['verifyCode', 'captcha'],
];
}
/**
* @return array customized attribute labels
*/
public function attributeLabels()
{
return [
'name' => 'Name:',
'email' => 'Email:',
'title' => 'Title:',
'body' => 'Connect with us :)',
'verifyCode' => 'Verification Code'
];
}
/**
* Sends an email to the specified email address using the information collected by this model.
* @param string $email the target email address
* @return bool whether the model passes validation
*/
public function contact($email)
{
if ($this->validate()) {
Yii::$app->mailer->compose()
->setTo($email)
->setFrom([$this->email => $this->name])
->setSubject($this->subject)
->setTextBody($this->body)
->send();
return true;
}
return false;
}
}
答案 0 :(得分:1)
我不会在开头使用条款和代码来阻止你。只需检查你的Google帐户中安全性较低的应用是否为OFF。如果它是ON,则将其关闭。如果所有设置都正确则可以是意想不到的故障。如果这没有帮助,请回复我。 在配置中添加smtp配置后,我用它来发送我的电子邮件(我也不记得在配置中添加任何额外的参数):
$value=Yii::$app->mailer->compose()
->setFrom('tomaivanovtomov@gmail.com')
->setTo($model->emailAddress)
->setSubject($model->subject)
->setHtmlBody($model->content)
->attach($model->attachment)
->send();
其中emailAddress将在填写表单时由各种用户填写,如果你有一个。如果不是这样,你将电子邮件存储在别处,那么你将不得不在php变量中获取它们并替换它们$ model-&gt;带有该变量的emailAddress。