ContactForm.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace frontend\models;
  3. use Yii;
  4. use yii\base\Model;
  5. /**
  6. * ContactForm is the model behind the contact form.
  7. */
  8. class ContactForm extends Model
  9. {
  10. public $name;
  11. public $email;
  12. public $subject;
  13. public $body;
  14. public $verifyCode;
  15. /**
  16. * @inheritdoc
  17. */
  18. public function rules()
  19. {
  20. return [
  21. // name, email, subject and body are required
  22. [['name', 'email', 'subject', 'body'], 'required'],
  23. // email has to be a valid email address
  24. ['email', 'email'],
  25. // verifyCode needs to be entered correctly
  26. ['verifyCode', 'captcha'],
  27. ];
  28. }
  29. /**
  30. * @inheritdoc
  31. */
  32. public function attributeLabels()
  33. {
  34. return [
  35. 'verifyCode' => '验证码',
  36. 'name' => '姓名',
  37. 'email' => '电子邮件',
  38. 'subject' => '主题',
  39. 'body' => '内容',
  40. ];
  41. }
  42. /**
  43. * Sends an email to the specified email address using the information collected by this model.
  44. *
  45. * @param string $email the target email address
  46. * @return bool whether the email was sent
  47. */
  48. public function sendEmail($email)
  49. {
  50. return Yii::$app->mailer->compose()
  51. ->setTo($email)
  52. ->setFrom([$this->email => $this->name])
  53. ->setSubject($this->subject)
  54. ->setTextBody($this->body)
  55. ->send();
  56. }
  57. }