Email.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php namespace Msg\Lib\Method;
  2. use Dever;
  3. class Email
  4. {
  5. private $config;
  6. # 初始化
  7. public function init($template_id, $config_id, $account, $project = 'api')
  8. {
  9. if (!Dever::project('email')) {
  10. Dever::error('账户不存在');
  11. }
  12. if (empty($account['email'])) {
  13. Dever::error('账户不存在');
  14. }
  15. $msg = 'msg';
  16. if ($project != 'api') {
  17. $msg = $project;
  18. }
  19. $this->config = Dever::db('account_email', $msg)->find(['account_id' => $config_id]);
  20. if (!$this->config) {
  21. Dever::error('邮件配置不存在');
  22. }
  23. $this->config['account'] = $account['email'];
  24. return $this->config['account'];
  25. }
  26. # 发送短信
  27. public function send($api, $content, $param)
  28. {
  29. if (!$this->config) {
  30. Dever::error('短信配置不存在');
  31. }
  32. Dever::apply('PHPMailer', 'email', 'src');
  33. Dever::apply('Exception', 'email', 'src');
  34. Dever::apply('SMTP', 'email', 'src');
  35. $mail = new \PHPMailer\PHPMailer\PHPMailer();
  36. list($host, $port) = explode(':', $this->config['host']);
  37. $mail->isSMTP();
  38. //$mail->SMTPDebug = 2;
  39. $mail->CharSet = 'UTF-8';
  40. $mail->Host = $host;
  41. $mail->Port = $port;
  42. if ($port == 465) {
  43. $mail->SMTPSecure = 'ssl';
  44. } else {
  45. $mail->SMTPSecure = 'tls';
  46. }
  47. $mail->SMTPAuth = true;
  48. $mail->Username = $this->config['user'];
  49. $mail->Password = $this->config['pwd'];
  50. $mail->setFrom($this->config['user'], $this->config['username']);
  51. $mail->addAddress($this->config['account'], $this->config['account']);
  52. if (empty($param['title'])) {
  53. $param['title'] = $this->config['title'];
  54. }
  55. $mail->Subject = "=?utf-8?B?" . base64_encode($param['title']) . "?=";
  56. $mail->Body = $content;
  57. $mail->isHTML(true);
  58. if (isset($param['file'])) {
  59. $mail->addAttachment($param['file']);
  60. }
  61. if (!$mail->send()) {
  62. $param['error'] = $mail->ErrorInfo;
  63. Dever::log($param, 'email');
  64. Dever::error("Mailer Error: " . $mail->ErrorInfo);
  65. } else {
  66. return 'ok';
  67. }
  68. }
  69. }