您的位置:首页 > 编程语言 > PHP开发

Yii 2发送带附件的邮件

2015-06-08 01:10 639 查看
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,
]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: