MailExport.php 19.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
<?php

namespace Service;

use Lib\Err;
use PHPMailer\PHPMailer\PHPMailer;

/**
 * 邮件导出为 eml 文件
 *
 * 逻辑来源 cmd/export_mail.php,这里抽成服务类,支持传入
 * postid(公司项目)、导出范围、数量上限,供页面调用。
 *
 * @author:dc
 * @time 2026/10/28 11:40
 * Class MailExport
 * @package Service
 */
class MailExport {

    /**
     * 星标邮件(所有文件夹)
     */
    public const SCOPE_STARRED = 'starred';

    /**
     * 收件箱全部
     */
    public const SCOPE_INBOX = 'inbox';

    /**
     * 默认导出数量
     */
    public const DEFAULT_LIMIT = 300;

    /**
     * 单次最大导出数量
     */
    public const MAX_LIMIT = 2000;

    /**
     * 清单文件名
     */
    private const MANIFEST_NAME = '导出清单.csv';

    /**
     * @var int 项目id
     */
    private int $postid = 0;

    /**
     * @var string 导出范围
     */
    private string $scope = '';

    /**
     * @var int 数量上限
     */
    private int $limit = 0;

    /**
     * @var string 本次导出目录
     */
    private string $dir = '';

    /**
     * @var array es _id 去重
     */
    private array $ids = [];

    /**
     * @var array 已生成的 eml 文件
     */
    private array $files = [];

    /**
     * @var array 已使用过的文件名,避免同一批里重名
     */
    private array $usedNames = [];

    /**
     * @var array 清单数据
     */
    private array $manifest = [];

    /**
     * @var array 失败记录
     */
    private array $errors = [];

    /**
     * @var int 成功数量
     */
    private int $success = 0;

    /**
     * @var int 失败数量
     */
    private int $fail = 0;

    /**
     * 导出范围
     * @return string[]
     * @author:dc
     * @time 2026/10/28 11:40
     */
    public static function scopeMap():array {
        return [
            self::SCOPE_STARRED => '星标邮件(所有文件夹)',
            self::SCOPE_INBOX   => '收件箱全部',
        ];
    }

    /**
     * 导出文件根目录
     * 说明:不放在 public 下面,只能通过页面鉴权后下载
     * @return string
     * @author:dc
     * @time 2026/10/28 11:40
     */
    public static function baseDir():string {
        return ROOT_PATH.'/storage/export';
    }

    /**
     * 查询命中的邮件数量
     * 返回 -1 表示 es 查询异常,与「0 封」区分开
     * @param int $postid
     * @param string $scope
     * @return int
     * @author:dc
     * @time 2026/10/28 11:40
     */
    public static function count(int $postid,string $scope):int {
        try {
            $count = es('email_lists_branch_'.$postid)->count(['query' => self::query($scope)], true);
            return max(0, intval($count));
        }catch (\Throwable $e){
            logs('邮件导出统计失败 postid:'.$postid.' '.$e->getMessage());
            return -1;
        }
    }

    /**
     * es 查询条件
     * 与 cmd/export_mail.php 保持一致:只取 ai 邮箱(source=2)、未删除
     * @param string $scope
     * @return array
     * @author:dc
     * @time 2026/10/28 11:40
     */
    public static function query(string $scope):array {
        $must = [
            ['term' => ['source' => 2]],
            ['term' => ['deleted' => 0]],
        ];

        if($scope === self::SCOPE_STARRED){
            // 星标:不限文件夹
            $must[] = ['term' => ['flagged' => 1]];
            $must[] = ['terms' => ['folder_as_int' => [1, 2, 3, 4, 5]]];
        }else{
            // 收件箱全部(含星标、含未读已读)
            $must[] = ['term' => ['folder_as_int' => 1]];
        }

        return ['constant_score' => ['filter' => ['bool' => ['must' => $must]]]];
    }

    /**
     * 文件名净化,保留中文
     * @param string $name
     * @return string
     * @author:dc
     * @time 2026/10/28 11:40
     */
    public static function sanitize(string $name):string {
        $name = preg_replace('/[^\p{L}\p{N}_\-\.\(\)]+/u', '_', $name);
        $name = preg_replace('/_+/u', '_', (string)$name);
        return trim((string)$name, '_ .');
    }

    /**
     * 执行导出
     * @param int $postid 项目id
     * @param string $scope 导出范围
     * @param int $limit 数量上限
     * @return array
     * @throws Err
     * @author:dc
     * @time 2026/10/28 11:40
     */
    public function export(int $postid,string $scope,int $limit):array {
        if(!$postid){
            throw new Err('缺少公司项目');
        }
        if(!isset(self::scopeMap()[$scope])){
            throw new Err('导出条件不支持');
        }

        $this->postid = $postid;
        $this->scope = $scope;
        $this->limit = max(1, min($limit ?: self::DEFAULT_LIMIT, self::MAX_LIMIT));

        $startTime = microtime(true);

        // 导出目录,带随机后缀,避免重复
        $this->dir = self::baseDir().'/'.$postid.'_'.date('Ymd_His').'_'.substr(md5(uniqid('', true)), 0, 6);
        if(!is_dir($this->dir) && !@mkdir($this->dir, 0775, true) && !is_dir($this->dir)){
            throw new Err('导出目录创建失败,请检查 storage 目录权限');
        }

        $hits = $this->search();
        if(!$hits){
            $this->removeDir($this->dir);
            // 没有数据时再确认一次,区分「es 挂了」和「真的没有邮件」
            if(self::count($this->postid, $this->scope) < 0){
                throw new Err('es 查询失败,请稍后再试(已记录日志)');
            }
            throw new Err('没有命中任何邮件,换个条件再试');
        }

        foreach($hits as $hit){
            $this->saveOne($hit);
        }

        if(!$this->files){
            $this->removeDir($this->dir);
            $detail = $this->errors ? $this->errors[0]['message'] : '未知原因';
            throw new Err('全部邮件导出失败:'.$detail);
        }

        // 清单
        $this->writeManifest();

        // 打包
        $zipName = $this->postid.'_'.date('Ymd_His').'.zip';
        $zipFile = $this->dir.'/'.$zipName;
        $this->zip($zipFile);

        return [
            'postid'     => $this->postid,
            'scope'      => $this->scope,
            'scope_label'=> self::scopeMap()[$this->scope],
            'limit'      => $this->limit,
            'total'      => count($hits),
            'success'    => $this->success,
            'fail'       => $this->fail,
            'errors'     => array_slice($this->errors, 0, 20),
            'dir'        => str_replace(ROOT_PATH, '', $this->dir),
            'zip_name'   => $zipName,
            'zip_size'   => is_file($zipFile) ? filesize($zipFile) : 0,
            'download'   => '/mail-export/download?f='.rawurlencode(basename($this->dir).'/'.$zipName),
            'cost'       => round(microtime(true) - $startTime, 1),
        ];
    }

    /**
     * 查询 es
     * @return array
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function search():array {
        $res = es('email_lists_branch_'.$this->postid)->search(
            ['query' => self::query($this->scope)],
            0,
            $this->limit,
            ['udate' => 'desc']
        );

        return $res['hits']['hits'] ?? [];
    }

    /**
     * 导出一封
     * @param array $hit
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function saveOne(array $hit):void {
        $esId = (string)($hit['_id'] ?? '');
        if($esId === '' || isset($this->ids[$esId])){
            return;
        }
        $this->ids[$esId] = 1;

        $src = $hit['_source'] ?? [];
        $file = $this->fileName($src);
        $subject = (string)($src['subject'] ?? '');

        try {
            $this->saveEml($src, $file);

            if(!is_file($file) || filesize($file) <= 0){
                throw new \Exception('eml 文件为空');
            }

            $this->files[] = $file;
            $this->success++;
            $this->manifest[] = [
                'subject' => $subject,
                'from'    => $this->addressText($src['from'] ?? []),
                'to'      => $this->toText($src),
                'date'    => empty($src['udate']) ? '' : date('Y-m-d H:i:s', $src['udate']),
                'uuid'    => (string)($src['uuid'] ?? ''),
                'file'    => basename($file),
                'status'  => '成功',
            ];
        }catch (\Throwable $e){
            // 半成品删掉
            if(is_file($file)){
                @unlink($file);
            }
            $this->fail++;
            $this->errors[] = [
                'subject' => $subject,
                'uuid'    => (string)($src['uuid'] ?? ''),
                'message' => $e->getMessage(),
            ];
            logs('邮件导出失败 '.(string)($src['uuid'] ?? '').' : '.$e->getMessage());
        }
    }

    /**
     * 生成 eml(逻辑同 cmd/export_mail.php 的 save_eml)
     * @param array $src es 数据
     * @param string $file
     * @throws \Exception
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function saveEml(array $src,string $file):void {
        $mail = new PHPMailer(true);

        $from = $src['from'] ?? [];
        $fromEmail = is_array($from) ? ($from['email'] ?? '') : (string)$from;
        $fromName = is_array($from) ? ($from['name'] ?? '') : '';
        if(!$fromEmail){
            throw new \Exception('发件人为空');
        }
        $mail->setFrom($fromEmail, $fromName);

        // 收件人
        $toName = @json_decode((string)($src['to_name'] ?? ''), true);
        if(is_array($toName) && $toName){
            foreach($toName as $item){
                if(empty($item['email'])) continue;
                try {
                    $mail->addAddress($item['email'], $item['name'] ?? '');
                }catch (\Throwable $e){}
            }
        }
        if(!$mail->getToAddresses() && !empty($src['to'])){
            foreach(explode(',', (string)$src['to']) as $item){
                $item = trim($item);
                if($item === '') continue;
                try {
                    $mail->addAddress($item);
                }catch (\Throwable $e){}
            }
        }

        $mail->Subject = (string)($src['subject'] ?? '');

        $uuid = (string)($src['uuid'] ?? '');
        // uuid 实际是 lists 表的自增id
        $body = ctype_digit($uuid) ? getMailBody((int)$uuid) : [];
        $html = getBodyHtml($body);

        // 没有 body,尝试同步一次
        if(!$html && ctype_digit($uuid) && !empty($src['email_id']) && !empty($src['uid'])){
            try {
                $folder = db()->value(\Model\folderSql::first($src['folder_id'] ?? 0, 'origin_folder'));
                (new SyncMail($src['email_id']))->mail($folder, [(string)$src['uid']], true);
                $body = getMailBody((int)$uuid);
                $html = getBodyHtml($body);
            }catch (\Throwable $e){
                logs('邮件导出补拉正文失败 '.$uuid.' : '.$e->getMessage());
            }
        }

        // 正文为空也要能生成 eml(否则 PHPMailer 会报 Message body empty)
        $mail->Body = $html ?: '<div></div>';
        $mail->Encoding = 'quoted-printable';
        $mail->CharSet = 'utf-8';
        // 用 MessageDate 保留原始收发时间(不要用 addCustomHeader,会出两个 Date 头)
        if(!empty($src['udate'])){
            $mail->MessageDate = date('D, d M Y H:i:s O', intval($src['udate']));
        }
        if(!empty($src['uuid'])){
            $mail->addCustomHeader('Uuid', (string)$src['uuid']);
        }

        // 附件
        foreach((array)$body as $item){
            if(!empty($item['path']) && is_file($item['path'])){
                try {
                    $mail->addAttachment($item['path'], $item['filename'] ?? '');
                }catch (\Throwable $e){}
            }
        }

        // 抄送
        foreach($this->addressList($src['cc'] ?? '') as $cc){
            try {
                $mail->addCC($cc['email'], $cc['name']);
            }catch (\Throwable $e){}
        }
        // 密送
        foreach($this->addressList($src['bcc'] ?? '') as $bcc){
            try {
                $mail->addBCC($bcc['email'], $bcc['name']);
            }catch (\Throwable $e){}
        }

        $mail->isHTML(true);
        $mail->preSend();

        $content = $mail->getSentMIMEMessage();
        if(!$content){
            throw new \Exception('eml 内容生成失败');
        }

        if(file_put_contents($file, $content) === false){
            throw new \Exception('eml 写入失败');
        }
    }

    /**
     * cc / bcc 解析
     * @param mixed $value
     * @return array
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function addressList(mixed $value):array {
        if(empty($value)){
            return [];
        }
        $list = is_array($value) ? $value : (@json_decode((string)$value, true) ?: []);
        $ret = [];
        foreach($list as $item){
            if(!is_array($item)){
                $item = ['email' => (string)$item];
            }
            if(empty($item['email'])) continue;
            $ret[] = ['email' => $item['email'], 'name' => $item['name'] ?? ''];
        }
        return $ret;
    }

    /**
     * 发件人文本
     * @param mixed $from
     * @return string
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function addressText(mixed $from):string {
        if(is_array($from)){
            $email = $from['email'] ?? '';
            $name = $from['name'] ?? '';
            return $name ? "{$name} <{$email}>" : (string)$email;
        }
        return (string)$from;
    }

    /**
     * 收件人文本
     * @param array $src
     * @return string
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function toText(array $src):string {
        $toName = @json_decode((string)($src['to_name'] ?? ''), true);
        if(is_array($toName) && $toName){
            $arr = [];
            foreach($toName as $item){
                if(empty($item['email'])) continue;
                $arr[] = empty($item['name']) ? $item['email'] : "{$item['name']} <{$item['email']}>";
            }
            if($arr){
                return implode('; ', $arr);
            }
        }
        return (string)($src['to'] ?? '');
    }

    /**
     * 生成不重复的文件名
     * @param array $src
     * @return string
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function fileName(array $src):string {
        $name = self::sanitize((string)($src['subject'] ?? ''));
        if($name === ''){
            $name = '无主题';
        }
        $name = mb_substr($name, 0, 80);

        $date = empty($src['udate']) ? '' : date('Ymd_His', $src['udate']);
        $base = trim(($date ? $date.'_' : '').$name, '_');

        $fileName = $base.'.eml';
        if(isset($this->usedNames[$fileName]) || is_file($this->dir.'/'.$fileName)){
            $i = 1;
            while(isset($this->usedNames[$base.'('.$i.').eml']) || is_file($this->dir.'/'.$base.'('.$i.').eml')){
                $i++;
            }
            $fileName = $base.'('.$i.').eml';
        }

        $this->usedNames[$fileName] = 1;

        return $this->dir.'/'.$fileName;
    }

    /**
     * 写导出清单
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function writeManifest():void {
        $file = $this->dir.'/'.self::MANIFEST_NAME;
        $fp = @fopen($file, 'wb');
        if(!$fp){
            return;
        }
        // excel 打开不乱码
        fwrite($fp, "\xEF\xBB\xBF");
        fputcsv($fp, ['序号', '主题', '发件人', '收件人', '日期', 'UUID', '文件名', '状态']);

        $i = 0;
        foreach($this->manifest as $item){
            fputcsv($fp, [
                ++$i,
                $item['subject'],
                $item['from'],
                $item['to'],
                $item['date'],
                $item['uuid'],
                $item['file'],
                $item['status'],
            ]);
        }
        // 失败的也记一下
        foreach($this->errors as $item){
            fputcsv($fp, [++$i, $item['subject'], '', '', '', $item['uuid'], '', '失败:'.$item['message']]);
        }

        fclose($fp);
        $this->files[] = $file;
    }

    /**
     * 打包
     * @param string $zipFile
     * @throws Err
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function zip(string $zipFile):void {
        if(class_exists('\ZipArchive')){
            $zip = new \ZipArchive();
            if($zip->open($zipFile, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) === true){
                foreach($this->files as $file){
                    $zip->addFile($file, basename($file));
                }
                if($zip->close() && is_file($zipFile) && filesize($zipFile) > 0){
                    return;
                }
            }
        }

        // 没有 zip 扩展时用不压缩的 zip
        $this->storeZip($zipFile);

        if(!is_file($zipFile) || filesize($zipFile) <= 0){
            throw new Err('打包失败,请检查 php-zip 扩展或目录权限');
        }
    }

    /**
     * 不压缩的 zip(无 php-zip 扩展时的兜底)
     * @param string $zipFile
     * @throws Err
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function storeZip(string $zipFile):void {
        $fp = @fopen($zipFile, 'wb');
        if(!$fp){
            throw new Err('zip 文件创建失败');
        }

        $central = '';
        $offset = 0;
        $count = 0;

        foreach($this->files as $file){
            $data = @file_get_contents($file);
            if($data === false){
                continue;
            }
            $name = basename($file);
            $crc = crc32($data);
            $size = strlen($data);
            $nameLen = strlen($name);
            $mtime = @filemtime($file) ?: time();
            $dosTime = (int)((date('H', $mtime) << 11) | (date('i', $mtime) << 5) | (date('s', $mtime) / 2));
            $dosDate = (int)(((date('Y', $mtime) - 1980) << 9) | (date('n', $mtime) << 5) | date('j', $mtime));

            // 本地文件头,0x0800 表示文件名是 utf-8
            $local = pack('VvvvvvVVVvv', 0x04034b50, 20, 0x0800, 0, $dosTime, $dosDate, $crc, $size, $size, $nameLen, 0).$name;
            fwrite($fp, $local);
            fwrite($fp, $data);

            // 中央目录
            $central .= pack('VvvvvvvVVVvvvvvVV', 0x02014b50, 20, 20, 0x0800, 0, $dosTime, $dosDate, $crc, $size, $size, $nameLen, 0, 0, 0, 0, 0, $offset).$name;

            $offset += strlen($local) + $size;
            $count++;
        }

        fwrite($fp, $central);
        fwrite($fp, pack('VvvvvVVv', 0x06054b50, 0, 0, $count, $count, strlen($central), $offset, 0));
        fclose($fp);
    }

    /**
     * 删除本次导出目录
     * @param string $dir
     * @author:dc
     * @time 2026/10/28 11:40
     */
    private function removeDir(string $dir):void {
        if(!$dir || !is_dir($dir)){
            return;
        }
        foreach((array)@scandir($dir) as $item){
            if($item === '.' || $item === '..' || $item === false){
                continue;
            }
            $path = $dir.'/'.$item;
            if(is_file($path)){
                @unlink($path);
            }
        }
        @rmdir($dir);
    }

}