ContactForm.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace app\models;
  3. use yii\base\Model;
  4. /**
  5. * ContactForm is the model behind the contact form.
  6. */
  7. class ContactForm extends Model
  8. {
  9. public $name;
  10. public $email;
  11. public $subject;
  12. public $body;
  13. public $verifyCode;
  14. /**
  15. * @return array the validation rules.
  16. */
  17. public function rules()
  18. {
  19. return array(
  20. // name, email, subject and body are required
  21. array('name, email, subject, body', 'required'),
  22. // email has to be a valid email address
  23. array('email', 'email'),
  24. // verifyCode needs to be entered correctly
  25. array('verifyCode', 'captcha'),
  26. );
  27. }
  28. /**
  29. * @return array customized attribute labels
  30. */
  31. public function attributeLabels()
  32. {
  33. return array(
  34. 'verifyCode' => 'Verification Code',
  35. );
  36. }
  37. /**
  38. * Sends an email to the specified email address using the information collected by this model.
  39. * @param string $email the target email address
  40. * @return boolean whether the model passes validation
  41. */
  42. public function contact($email)
  43. {
  44. if ($this->validate()) {
  45. $name = '=?UTF-8?B?' . base64_encode($this->name) . '?=';
  46. $subject = '=?UTF-8?B?' . base64_encode($this->subject) . '?=';
  47. $headers = "From: $name <{$this->email}>\r\n" .
  48. "Reply-To: {$this->email}\r\n" .
  49. "MIME-Version: 1.0\r\n" .
  50. "Content-type: text/plain; charset=UTF-8";
  51. mail($email, $subject, $this->body, $headers);
  52. return true;
  53. } else {
  54. return false;
  55. }
  56. }
  57. }