Mail.php 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. * Created by PhpStorm
  4. * User Julyssn
  5. * Date 2021/8/3 13:50
  6. */
  7. namespace mail;
  8. use Swift_Mailer;
  9. use Swift_Message;
  10. use Swift_SmtpTransport;
  11. use think\facade\View;
  12. class Mail
  13. {
  14. public $Config = [
  15. 'driver' => 'smtp', // 邮件驱动, 支持 smtp|sendmail|mail 三种驱动
  16. 'host' => 'smtp.qq.com', // SMTP服务器地址
  17. 'port' => 465, // SMTP服务器端口号,一般为25
  18. 'addr' => '', // 发件邮箱地址
  19. 'pass' => '', // 发件邮箱密码
  20. 'sign' => '', // 发件邮箱名称
  21. 'content_type' => 'text/html', // 默认文本内容 text/html|text/plain
  22. 'charset' => 'utf-8', // 默认字符集
  23. 'security' => 'ssl', // 加密方式 null|ssl|tls, QQ邮箱必须使用ssl
  24. 'temp' => '', //邮件模板
  25. 'logo' => '', //邮件logo
  26. ];
  27. public function __construct($config)
  28. {
  29. $this->Config = array_merge($this->Config, $config);
  30. //默认模板
  31. $this->Config['temp'] = $this->Config['temp'] ?: 'temp';
  32. $this->Config['logo'] = $this->Config['logo'] ?: 'https://im.file.raingad.com/logo/logo.png';
  33. }
  34. public function sendEmail(array $toEmails, $title, $content)
  35. {
  36. // 创建Transport对象,设置邮件服务器和端口号,并设置用户名和密码以供验证
  37. $transport = (new Swift_SmtpTransport($this->Config['host'], $this->Config['port'], $this->Config['security']))
  38. ->setUsername($this->Config['addr'])
  39. ->setPassword($this->Config['pass']);
  40. //创建mailer对象
  41. $mailer = new Swift_Mailer($transport);
  42. //创建message对象
  43. $message = (new Swift_Message($title));//设置邮件主题
  44. //用关联数组设置发件人地址,可以设置多个发件人
  45. $message->setFrom([$this->Config['addr'] => $this->Config['sign']]);
  46. //用关联数组设置收件人地址,可以设置多个收件人
  47. $message->setTo($toEmails);
  48. //设置邮件内容
  49. $data = [
  50. 'logo' => $this->Config['logo'],
  51. 'title' => $title,
  52. 'content' => $content,
  53. 'time' => date('Y-m-d H:i:s'),
  54. 'name' => $this->Config['sign']
  55. ];
  56. $html = View::fetch(dirname(__FILE__) . '/' . $this->Config['temp'] . '.html', ['data' => $data]);
  57. $message->setBody($html, 'text/html');
  58. // //创建attachment对象,content-type这个参数可以省略
  59. // $attachment = Swift_Attachment::fromPath('image.jpg', 'image/jpeg')->setFilename('cool.jpg');
  60. // //添加附件
  61. // $message->attach($attachment);
  62. // //添加抄送人
  63. // $message->setCc(array(
  64. // 'Cc@qq.com' => 'Cc'
  65. // ));
  66. // //添加密送人
  67. // $message->setBcc(array(
  68. // 'Bcc@qq.com' => 'Bcc'
  69. // ));
  70. // //设置邮件回执
  71. // $message->setReadReceiptTo('receipt@163.com');
  72. //发送邮件
  73. return $mailer->send($message);
  74. }
  75. }