Yii 2发送带附件的邮件
首先使用gii创建下面这张表的Model和curd方法
创建成功后,在配置文件的components中添加
- 'mailer' => [
- 'class' => 'yii\swiftmailer\Mailer',
- 'viewPath' => '@common/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' => true,
- ],
在web目录下新建attachments目录,然后把emails控制器的create方法改为
上传附件,发送邮件,即可看到发送成功(需要你服务器的支持,本地是收不到邮件的)!
- public function actionCreate()
- {
- $model = new Emails();
-
- if ($model->load(Yii::$app->request->post())) {
- $model->attachment = UploadedFile::getInstance($model, 'attachment');
- if ($model->attachment) {
- $time = time();
- $model->attachment->saveAs('attachments/' . $time . '.' . $model->attachment->extension);
- $model->attachment = 'attachments/' . $time . '.' . $model->attachment->extension;
- }
- if ($model->attachment) {
- $value = Yii::$app->mailer->compose()
- ->setFrom(["372945452@qq.com" => "cnsecer"])
- ->setTo($model->receiver_email)
- ->setSubject($model->subject)
- ->setHtmlBody($model->content)
- ->attach($model->attachment)
- ->send();
- } else {
- $value = Yii::$app->mailer->compose()
- ->setFrom(["372945452@qq.com" => "cnsecer"])
- ->setTo($model->receiver_email)
- ->setSubject($model->subject)
- ->setHtmlBody($model->content)
- ->send();
- }
- $model->save();
- return $this->redirect(['view', 'id' => $model->id]);
- } else {
- return $this->render('create', [
- 'model' => $model,
- ]);
- }
- }