MailService.php 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Leo.xie
  5. * Date: 2017/7/28
  6. * Time: 9:47
  7. * Description:邮件发送服务
  8. */
  9. namespace app\common\service;
  10. use think\Log;
  11. use PHPMailer\PHPMailer\PHPMailer;
  12. class MailService {
  13. private $account = [
  14. // ['account'=>'811329263@qq.com','key'=>'jwxrmfukwalobbhi'],
  15. ['account' => '2990412861@qq.com', 'key' => 'tayeekdedupfdfgc'], //IMAP/SMTP服务
  16. ];
  17. /**
  18. * @param string $sendName 给自己作为发送者设置的姓名
  19. * @param string $subject 邮件的标题【主题】名称
  20. * @param string $content 邮件的内容是什么
  21. * @param string $replyMail 要求邮件回复给谁
  22. * @param array $toMail 发送邮件给谁的列表 [0=>['mail'=>'xx@qq.com','name'=>'xx']]
  23. * @param string $fromMail
  24. * @return bool
  25. */
  26. public function send(string $sendName,
  27. string $subject,
  28. string $content,
  29. string $replyMail,
  30. $toMail = [],
  31. $fromMail = ''): bool {
  32. if (!$sendName || !$subject || !$content || !$toMail) {
  33. HelperService::$_httpErr = 'Mail params is error';
  34. return false;
  35. }
  36. date_default_timezone_set('Asia/Shanghai');
  37. // 随机邮箱账户
  38. $randomAccount = $this->account[random_int(0, count($this->account) - 1)];
  39. $mail = new PHPMailer(); //得到一个PHPMailer实例
  40. $mail->CharSet = "utf-8"; //设置采用utf-8中文编码(内容不会乱码)
  41. $mail->isSMTP(); //设置采用SMTP方式发送邮件
  42. $mail->Host = "smtp.qq.com"; //设置邮件服务器的地址(若为163邮箱,则是smtp.163.com)
  43. // $mail->Host = "ssl://smtp.qq.com"; //设置邮件服务器的地址(若为163邮箱,则是smtp.163.com)
  44. $mail->Port = 465; //设置邮件服务器的端口,默认为25
  45. $mail->From = empty($fromMail) ? $randomAccount['account'] : $fromMail; //设置发件人的邮箱地址
  46. $mail->FromName = $sendName; //设置发件人的姓名(可随意)
  47. $mail->SMTPAuth = true; //设置SMTP是否需要密码验证,true表示需要
  48. $mail->SMTPSecure = 'ssl';
  49. $mail->Username = $randomAccount['account']; //(后面有解释说明为何设置为发件人)
  50. $mail->Password = $randomAccount['key']; // 密码
  51. $mail->Subject = $subject; //主题
  52. $mail->AltBody = "text/html"; // optional, comment out and test
  53. $mail->Body = $content; //内容
  54. $mail->isHTML(true);
  55. $mail->WordWrap = 50; //设置每行的字符数
  56. if (empty($replyMail)) {
  57. $replyMail = $randomAccount['account'];
  58. }
  59. $mail->addReplyTo((string)($replyMail), "from"); //设置回复的收件人的地址(from可随意)
  60. foreach ($toMail as $mailItem) {
  61. if (!$mailItem['mail'] || !$mailItem['name']) {
  62. continue;
  63. }
  64. $mail->addAddress($mailItem['mail'], $mailItem['name']); //设置收件的地址(to可随意)
  65. }
  66. try {
  67. return $mail->send();
  68. } catch (\Exception $ex) {
  69. Log::record('邮件发送失败:' . $ex->getMessage());
  70. HelperService::$_httpErr = $ex->getMessage();
  71. return false;
  72. }
  73. }
  74. }