Yii 2发送带附件的邮件

通过Yii 2框架,使用gii生成Model和CRUD操作,配置components并在web目录下创建attachments文件夹用于存储附件。在emails控制器的create方法中实现文件上传并发送带附件的邮件,邮件发送需依赖服务器支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Yii 2发送带附件的邮件

首先使用gii创建下面这张表的Model和curd方法


创建成功后,在配置文件的components中添加

  1. 'mailer' => [
  2. 'class' => 'yii\swiftmailer\Mailer',
  3. 'viewPath' => '@common/mail',
  4. // send all mails to a file by default. You have to set
  5. // 'useFileTransport' to false and configure a transport
  6. // for the mailer to send real emails.
  7. 'useFileTransport' => true,
  8. ],

在web目录下新建attachments目录,然后把emails控制器的create方法改为

上传附件,发送邮件,即可看到发送成功(需要你服务器的支持,本地是收不到邮件的)!

  1. public function actionCreate()
  2. {
  3. $model = new Emails();
  4.  
  5. if ($model->load(Yii::$app->request->post())) {
  6. $model->attachment = UploadedFile::getInstance($model, 'attachment');
  7. if ($model->attachment) {
  8. $time = time();
  9. $model->attachment->saveAs('attachments/' . $time . '.' . $model->attachment->extension);
  10. $model->attachment = 'attachments/' . $time . '.' . $model->attachment->extension;
  11. }
  12. if ($model->attachment) {
  13. $value = Yii::$app->mailer->compose()
  14. ->setFrom(["372945452@qq.com" => "cnsecer"])
  15. ->setTo($model->receiver_email)
  16. ->setSubject($model->subject)
  17. ->setHtmlBody($model->content)
  18. ->attach($model->attachment)
  19. ->send();
  20. } else {
  21. $value = Yii::$app->mailer->compose()
  22. ->setFrom(["372945452@qq.com" => "cnsecer"])
  23. ->setTo($model->receiver_email)
  24. ->setSubject($model->subject)
  25. ->setHtmlBody($model->content)
  26. ->send();
  27. }
  28. $model->save();
  29. return $this->redirect(['view', 'id' => $model->id]);
  30. } else {
  31. return $this->render('create', [
  32. 'model' => $model,
  33. ]);
  34. }
  35. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值