Mail.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. use Nette\Mail\Message;
  3. use Nette\Mail\SmtpMailer;
  4. use \app\model\SettingModel;
  5. class Mail
  6. {
  7. public static function send($to = "", $text = ""): bool
  8. {
  9. $mail = new Message;
  10. $send_mail = SettingModel::Config('smtp_email', false);
  11. $option = [
  12. 'port' => SettingModel::Config('smtp_port'),
  13. 'host' => SettingModel::Config('smtp_host', false),
  14. 'username' => SettingModel::Config('smtp_email'),
  15. 'password' => SettingModel::Config('smtp_password'),
  16. ];
  17. if (!$send_mail || !$option['host']) {
  18. return abort(0, "管理员没有配置SMTP邮件服务");
  19. }
  20. $mail->setFrom(SettingModel::Config('title', '') . " <$send_mail>")
  21. ->addTo($to)
  22. ->setSubject(SettingModel::Config('title', '') . '动态令牌')
  23. ->setHtmlBody($text);
  24. $ssl = (int)SettingModel::Config('smtp_ssl', '0');
  25. if (in_array($ssl, [1, 2, 3])) {
  26. if ($ssl === 2) {
  27. $option['secure'] = 'ssl';
  28. }
  29. if ($ssl === 3) {
  30. $option['secure'] = 'tls';
  31. }
  32. } else {
  33. if ((int)$option['port'] === 465) {
  34. $option['secure'] = 'ssl';
  35. }
  36. if ((int)$option['port'] === 587) {
  37. $option['secure'] = 'tls';
  38. }
  39. }
  40. try {
  41. $mailer = new SmtpMailer($option);
  42. $mailer->send($mail);
  43. return true;
  44. } catch (\Exception $e) {
  45. if ($e->getMessage() === 'Connection has been closed unexpectedly.') {
  46. return true;
  47. }
  48. throw new \Exception($e->getMessage());
  49. }
  50. }
  51. public static function testMail($to, $config): bool
  52. {
  53. $mail = new Message;
  54. $send_mail = $config['smtp_email'];
  55. $mail->setFrom("测试邮件 <$send_mail>")
  56. ->addTo($to)
  57. ->setSubject('测试邮件')
  58. ->setHtmlBody("这是一个测试邮件");
  59. $option = [
  60. 'port' => $config['smtp_port'],
  61. 'host' => $config['smtp_host'],
  62. 'username' => $config['smtp_email'],
  63. 'password' => $config['smtp_password'],
  64. ];
  65. $ssl = (int)($config['smtp_ssl'] ?? '0');
  66. if (in_array($ssl, [1, 2, 3])) {
  67. if ($ssl === 2) {
  68. $option['secure'] = 'ssl';
  69. }
  70. if ($ssl === 3) {
  71. $option['secure'] = 'tls';
  72. }
  73. } else {
  74. if ((int)$option['port'] === 465) {
  75. $option['secure'] = 'ssl';
  76. }
  77. if ((int)$option['port'] === 587) {
  78. $option['secure'] = 'tls';
  79. }
  80. }
  81. try {
  82. $mailer = new SmtpMailer($option);
  83. $mailer->send($mail);
  84. return true;
  85. } catch (\Exception $e) {
  86. if ($e->getMessage() === 'Connection has been closed unexpectedly.') {
  87. return true;
  88. }
  89. throw new \Exception($e->getMessage());
  90. }
  91. }
  92. }