SmtpSend.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace App\Com;
  3. use EasySwoole\EasySwoole\Config;
  4. use PHPMailer\PHPMailer\PHPMailer;
  5. use PHPMailer\PHPMailer\SMTP;
  6. use PHPMailer\PHPMailer\Exception;
  7. use EasySwoole\EasySwoole\Logger;
  8. class SmtpSend
  9. {
  10. protected $mail; //用于存放phpmailer对象
  11. protected $send_mail; //发送人邮件地址
  12. function __construct()
  13. {
  14. $smtp_config = Config::getInstance()->getConf('SMTP_SET'); //获取邮箱设置
  15. $this->send_mail = $smtp_config['username'];
  16. $this->mail = new PHPMailer(true);
  17. //$this->mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
  18. $this->mail->isSMTP(); //Send using SMTP
  19. $this->mail->CharSet = 'UTF-8';
  20. $this->mail->Host = $smtp_config['host']; //Set the SMTP server to send through
  21. $this->mail->SMTPAuth = true; //Enable SMTP authentication
  22. $this->mail->Username = $this->send_mail; //SMTP username
  23. $this->mail->Password = $smtp_config['password']; //SMTP password
  24. $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
  25. $this->mail->Port = $smtp_config['port'];
  26. }
  27. /**
  28. * 邮件发送
  29. * @param $toAddress 接受邮件的邮箱地址
  30. * @param $subject 邮件标题
  31. * @param $body 邮件内容
  32. * @param $isHtml 邮件内容是否是html,默认为否
  33. * @return Array 返回参数
  34. */
  35. public function send($toAddress,$subject,$body,$isHtml=false){
  36. try {
  37. //Recipients
  38. $this->mail->setFrom($this->send_mail);
  39. $this->mail->addAddress($toAddress); //Add a recipient
  40. //Content
  41. $this->mail->isHTML($isHtml); //Set email format to HTML
  42. $this->mail->Subject = $subject;
  43. $this->mail->Body = $body;
  44. $this->mail->AltBody = '您的邮箱不支持HTML格式,请联系邮箱管理员';
  45. $this->mail->send();
  46. $notice = "smtp邮件发送成功,内容:".json_encode(['toAddress'=>$toAddress,'subject'=>$subject,'body'=>$body])."\n";
  47. Logger::getInstance()->notice($notice);
  48. return true;
  49. } catch (Exception $e) {
  50. $notice = "smtp邮件发送失败. 错误信息: {$this->mail->ErrorInfo},内容:".json_encode(['toAddress'=>$toAddress,'subject'=>$subject,'body'=>$body])."\n";
  51. Logger::getInstance()->notice($notice);
  52. return false;
  53. }
  54. }
  55. }