MailerService.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace services\common;
  3. use Yii;
  4. use yii\base\InvalidConfigException;
  5. use common\queues\MailerJob;
  6. /**
  7. * Class MailerService
  8. * @package services\common
  9. * @author jianyan74 <751393839@qq.com>
  10. */
  11. class MailerService
  12. {
  13. /**
  14. * 消息队列
  15. *
  16. * @var bool
  17. */
  18. public $queueSwitch = false;
  19. /**
  20. * @var array
  21. */
  22. protected $config = [];
  23. /**
  24. * 发送邮件
  25. *
  26. * ```php
  27. * Yii::$app->services->mailer->send($user, $email, $subject, $template)
  28. * ```
  29. * @param object $user 用户信息
  30. * @param string $email 邮箱
  31. * @param string $subject 标题
  32. * @param string $template 对应邮件模板
  33. * @throws \yii\base\InvalidConfigException
  34. */
  35. public function send($user, $email, $subject, $template, $data = [])
  36. {
  37. if ($this->queueSwitch == true) {
  38. $messageId = Yii::$app->queue->push(new MailerJob([
  39. 'user' => $user,
  40. 'email' => $email,
  41. 'subject' => $subject,
  42. 'template' => $template,
  43. 'data' => $data,
  44. ]));
  45. return $messageId;
  46. }
  47. return $this->realSend($user, $email, $subject, $template, $data);
  48. }
  49. /**
  50. * 发送
  51. *
  52. * @param $user
  53. * @param $email
  54. * @param $subject
  55. * @param $template
  56. * @return bool
  57. * @throws \yii\base\InvalidConfigException
  58. */
  59. public function realSend($user, $email, $subject, $template, $data = [])
  60. {
  61. try {
  62. $this->setConfig();
  63. $result = Yii::$app->mailer
  64. ->compose($template, [
  65. 'user' => $user,
  66. 'data' => $data,
  67. ])
  68. ->setFrom([$this->config['smtp_username'] => $this->config['smtp_name']])
  69. ->setTo($email)
  70. ->setSubject($subject)
  71. ->send();
  72. Yii::info($result);
  73. return $result;
  74. } catch (InvalidConfigException $e) {
  75. Yii::error($e->getMessage());
  76. }
  77. return false;
  78. }
  79. /**
  80. * @throws \yii\base\InvalidConfigException
  81. */
  82. protected function setConfig()
  83. {
  84. $this->config = Yii::$app->services->config->backendConfigAll();
  85. Yii::$app->set('mailer', [
  86. 'class' => 'yii\swiftmailer\Mailer',
  87. 'viewPath' => '@common/mail',
  88. 'transport' => [
  89. 'class' => 'Swift_SmtpTransport',
  90. 'host' => $this->config['smtp_host'],
  91. 'username' => $this->config['smtp_username'],
  92. 'password' => $this->config['smtp_password'],
  93. 'port' => $this->config['smtp_port'],
  94. 'encryption' => empty($this->config['smtp_encryption']) ? 'tls' : 'ssl',
  95. ],
  96. ]);
  97. }
  98. }
粤ICP备19079148号