--
這是一封由 Google Gmail 寄出的信件原始碼,主旨是 sdf 內容 sdf
|
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 |
From pc@hoyo.idv.tw Sun May 20 14:01:45 2018 Received: from mail-pl0-x236.google.com (unknown [IPv6:2607:f8b0:400e:c01::236]) by sm.hoyo.idv.tw (Postfix) with ESMTP id C94B9C2B30A2C for <oenru2@sm.hoyo.idv.tw>; Sun, 20 May 2018 06:01:44 +0000 (UTC) DKIM-Filter: OpenDKIM Filter v2.11.0 sm.hoyo.idv.tw C94B9C2B30A2C Authentication-Results: sm.hoyo.idv.tw; dkim=pass (2048-bit key) header.d=hoyo-idv-tw.20150623.gappssmtp.com header.i=@hoyo-idv-tw.20150623.gappssmtp.com header.b="0n6iLjVc" Received: by mail-pl0-x236.google.com with SMTP id ay10-v6so6907782plb.1 for <oenru2@sm.hoyo.idv.tw>; Sat, 19 May 2018 23:01:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=hoyo-idv-tw.20150623.gappssmtp.com; s=20150623; h=mime-version:from:date:message-id:subject:to; bh=zmipbNoRU4Htj2PidOeINnUwMC3J2OqqDT0EdnBpO08=; b=0n6iLjVcN/rZCA1gQDpF3kxCdnzz2JQZ/mhpx6nV0G4MIlBdeCg4Mx+RI3uGwCH1/Z mfrPSYZA9ncuTyNlry0sMH69sk5zlVx8LI0PJFsSruyBSDtShq6UmYG2mCIJvZYrLlRL 3nvM9ngH68JpgD757YaiVhOm79cAf57qAvEWo7e6+riwi5mbF2CowHc+p4EmBm9t763b lM7SLR3ColpTCDywstq6eZBeEAkB/EFlkCAoE8y2NOKgwx0VT97GwLpFxWIDMRP2assr GSeSauui1zpHmpGRZEnwt7wUTT3HwiDq9PsOtvl+vPmHUxeT79Xkd00/x/hU5X8X+AJy K4yA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:mime-version:from:date:message-id:subject:to; bh=zmipbNoRU4Htj2PidOeINnUwMC3J2OqqDT0EdnBpO08=; b=rviNB4QgamZtGALFTsAHCgBQ/Wp4cMphhOkMYweAIdvOyk3MysPfWd4LbykdrQF64P w+BDnzLZhuRWYFQKJvclkWUZn8CLEnzlfFos69CjbXKXEBy+z363SUQFZ/6CArYC7+A2 sQAA118UStijV1XWnrcRT/ceGd/+n1mB3bGCqHE1gjb3LurByzDYeX9rOqqR7ZgLA3l7 o89VBl/5TXDWE6xu22qWH3tyIRf/32NwMQAVkO7QReFyqbA9wrbUMVqr/EFPDDerALJu E2rRggwoxlApJR0+ha/RmMWfAxjNXNFxcQtUm0WyQO5DJA90dTAHnWUVPjVSC1eMN7bx LEbw== X-Gm-Message-State: ALKqPwfwoP/JRc6Y0ecepyjG0h7QrVq0v2mjHOlXNuz3uxuFUgUWnmh4 g7Tx/pY2EuoZUD7ThKmdGgjm0ZRwc4M+mRls7dcrOfgD X-Google-Smtp-Source: AB8JxZrm9IAfiocxS9p7XvPFJMCBP3tD8bpUuR57yCkbKJ4/dHRVHA9B3eIqV1svUQCqR7BRj6JIt26G8J3Yjz8DEck= X-Received: by 2002:a17:902:3103:: with SMTP id w3-v6mr15405047plb.37.1526796103596; Sat, 19 May 2018 23:01:43 -0700 (PDT) MIME-Version: 1.0 Received: by 10.100.181.171 with HTTP; Sat, 19 May 2018 23:01:43 -0700 (PDT) From: =?UTF-8?B?6buD5b+X6LOi?= <pc@hoyo.idv.tw> Date: Sun, 20 May 2018 14:01:43 +0800 Message-ID: <CAJ060EoTYq_UGkp-SVkvh6KUdk2JOBHFUrWPwkokijNg0sB9XA@mail.gmail.com> Subject: sdf To: oenru2@sm.hoyo.idv.tw Content-Type: multipart/alternative; boundary="000000000000664f74056c9ceba4" --000000000000664f74056c9ceba4 Content-Type: text/plain; charset="UTF-8" sdf --000000000000664f74056c9ceba4 Content-Type: text/html; charset="UTF-8" <div dir="ltr">sdf<br></div> --000000000000664f74056c9ceba4-- |
SMTP 本來在收到這封信時,會解析 To: 等內容確定這封信是要給誰,然後將信件歸到該使用者的檔案或資料夾內,使用者使用讀信軟體時就會進行內容解讀,將寄信人、收件人、主旨、內容等一般資訊列出
可是當我們要把信件呈現在網頁上時,就必須先把信件內容「翻譯」成網頁可以顯示的結果,例如 ?UTF-8?B?6buD5b+X6LOi?= 這種 RFC2047 的編碼方式,還有將不同的字元編碼統一轉成 UTF-8 等等等之類的工作
--
PHP 的信件解析函式庫
幸運的是 PHP 不愧是成熟的語言,什麼風浪都見過,針對信件有了專門的解析函式庫,不幸的是這是 PECL 所以需要另外安裝載入
--
安裝、載入 Mailparse
- Installing the PECL/PEAR mailparse module for PHP on CentOS
- How to Install php-mailparse in Ubuntu 18.04
Ubuntu
|
1 2 |
# apt install php-dev # apt install php-mailparse |
CentOS 7 + PHP 7.2
|
1 2 3 4 |
# yum install php-pear php-devel # pear channel-update pecl.php.net # yum install http://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/r/re2c-0.14.3-2.el7.x86_64.rpm # pear install pecl/mailparse |
CentOS 6 + php5.3
安裝 mailparse
|
1 2 |
# yum install re2c # pear install pecl/mailparse-2.1.6 |
--
載入 extension ,檔案必須自己產生
|
1 2 |
vi /etc/php.d/40-mailparse.ini extension=mailparse.so |
重新啟動 httpd
|
1 |
# systemctl restart httpd |
CentOS 6
|
1 |
/etc/rd.d/init.d/httpd restart |
--
AI 寫的 PHP 8.1
安裝依賴
|
1 |
apt install php8.5-xml php8.5-dom php8.5-mysql |
確認
|
1 |
php -m | grep pdo_mysql |
程式
|
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 |
#!/usr/bin/php <?php declare(strict_types=1); /** * Postfix pipe 收信程式(PHP 8.1 現代寫法重寫版) * * 用法: echo $mail | php hoyo_mail_parser.php user@domain.com * * 相容性備註: * - readonly 屬性、建構子屬性提升 (constructor property promotion)、 * match 表達式、具名參數 (named arguments) 皆為 PHP 8.0/8.1 語法, * 全部相容於 PHP 8.1,無需降級任何寫法。 */ // --------------------------------------------------------------------------- // 設定 / Configuration // --------------------------------------------------------------------------- final class Config { // 建議改用環境變數而非寫死在程式碼中,避免敏感資訊外洩。 public function __construct( public readonly string $mysqlHost = '', public readonly string $mysqlUsername = '', public readonly string $mysqlPassword = '', public readonly string $mysqlDbName = 'HOYO_Postfix', public readonly string $vmailPath = '/vmail/sm.hoyo.idv.tw', public readonly string $tmpPath = '/tmp', ) {} public static function fromEnv(): self { return new self( mysqlHost: getenv('HOYO_DB_HOST') ?: '', mysqlUsername: getenv('HOYO_DB_USER') ?: '', mysqlPassword: getenv('HOYO_DB_PASS') ?: '', mysqlDbName: getenv('HOYO_DB_NAME') ?: 'HOYO_Postfix', vmailPath: getenv('HOYO_VMAIL_PATH') ?: '/vmail/sm.hoyo.idv.tw', tmpPath: getenv('HOYO_TMP_PATH') ?: sys_get_temp_dir(), ); } public function dsn(): string { return sprintf( 'mysql:dbname=%s;host=%s;charset=utf8mb4', $this->mysqlDbName, $this->mysqlHost, ); } } // --------------------------------------------------------------------------- // 小工具 / Helpers // --------------------------------------------------------------------------- final class Helpers { /** 取得檔名的副檔名(不含點) */ public static function extFileName(string $name): string { $parts = explode('.', $name); return array_pop($parts) ?: ''; } } // --------------------------------------------------------------------------- // 附件資料值物件 / Attachment value object // --------------------------------------------------------------------------- final class MailAttachment { public function __construct( public readonly string $filename, public readonly string $base64Content, ) {} } // --------------------------------------------------------------------------- // 解析後信件內容 / Parsed mail body // --------------------------------------------------------------------------- final class MailBody { /** @var MailAttachment[] */ public array $files = []; public function __construct( public string $html = '', public string $plain = '', ) {} } // --------------------------------------------------------------------------- // 郵件解析器 / Mail parser // --------------------------------------------------------------------------- final class HoyoMailParser { /** @var array<string,string> */ public readonly array $header; public readonly MailBody $body; public function __construct(string $rawMail, private readonly string $tmpPath) { $body = new MailBody(); $mail = mailparse_msg_create(); mailparse_msg_parse($mail, $rawMail); $structure = mailparse_msg_get_structure($mail); $sections = []; foreach ($structure as $sectionId) { $sections[] = mailparse_msg_get_part($mail, $sectionId); } $info = array_map( static fn ($section) => mailparse_msg_get_part_data($section), $sections, ); // 信件標頭 $header = []; foreach ($info[0]['headers'] ?? [] as $key => $value) { if (is_string($value)) { $header[$key] = mb_decode_mimeheader($value); } } $this->header = $header; $attachmentIndex = 0; foreach ($sections as $i => $section) { $partData = ''; mailparse_msg_extract_part( $section, $rawMail, static function (string $chunk) use (&$partData): void { $partData .= $chunk; }, ); $partHeaders = $info[$i]['headers'] ?? []; if (($partHeaders['transfer-encoding'] ?? '') === '8bit') { $partData = mb_decode_mimeheader($partData); } $charset = strtolower($info[$i]['charset'] ?? 'utf-8'); if ($charset !== 'utf-8') { $partData = mb_convert_encoding($partData, 'UTF-8', $charset); } // RFC 2045:缺少 Content-Type 標頭時,預設視為 text/plain。 // 這種沒有 MIME boundary、純文字直接寄送的信件(例如用 mail/mailx // 指令寄出)常常完全不帶 Content-Type,若預設成空字串, // 底下的比對會全部落空,導致內文抓不到、存進資料庫的欄位是空的。 $contentType = $partHeaders['content-type'] ?? 'text/plain'; match (true) { (bool) preg_match('/text\/html/i', $contentType) => $body->html = $partData, (bool) preg_match('/text\/plain/i', $contentType) => $body->plain = $partData, default => null, }; $attachmentId = $partHeaders['x-attachment-id'] ?? null; if ($attachmentId === null) { continue; } $decodedContentType = mb_decode_mimeheader($contentType); $extParts = explode('.', $decodedContentType); $extension = trim((string) array_pop($extParts), '"'); file_put_contents( "{$this->tmpPath}/{$attachmentId}.{$extension}", $partData, ); $disposition = $partHeaders['content-disposition'] ?? ''; $isInline = (bool) preg_match('/inline/i', $disposition); if ($isInline) { $body->html = str_replace( "cid:{$attachmentId}", 'data:' . ($info[$i]['content-type'] ?? '') . ';base64,' . base64_encode($partData), $body->html, ); $body->files[$attachmentIndex] = new MailAttachment( filename: mb_decode_mimeheader($info[$i]['disposition-filename'] ?? "attachment-{$attachmentIndex}"), base64Content: base64_encode($partData), ); $attachmentIndex++; } if (($info[$i]['content-disposition'] ?? '') === 'attachment') { $body->files[$attachmentIndex] = new MailAttachment( filename: mb_decode_mimeheader($info[$i]['disposition-filename'] ?? "attachment-{$attachmentIndex}"), base64Content: base64_encode($partData), ); $attachmentIndex++; } } $this->body = $body; } } // --------------------------------------------------------------------------- // HTML 清理 / HTML sanitising (uses phpQuery) // --------------------------------------------------------------------------- final class HtmlSanitiser { public static function clean(string $html): string { $dom = \phpQuery::newDocument($html); $dom->find('head, style, script, link, form')->remove(); $dom->find('a')->attr('target', '_blank'); return (string) $dom; } } // --------------------------------------------------------------------------- // 資料存取 / Repository // --------------------------------------------------------------------------- final class MailRepository { public function __construct(private readonly PDO $pdo) {} public function logRawMail(string $rawMail): void { $stmt = $this->pdo->prepare('INSERT INTO Log (Mail) VALUES (:Mail)'); $stmt->execute(['Mail' => $rawMail]); } /** * @param array<string,string> $fields */ public function insertInbox(array $fields): int { $stmt = $this->pdo->prepare(<<<SQL INSERT INTO Inbox (Source, message_id, `To`, `From`, FromName, FromEmail, Subject, ContentTEXT, ContentHTML) VALUES (:Source, :message_id, :To, :From, :FromName, :FromEmail, :Subject, :ContentTEXT, :ContentHTML) SQL); $stmt->execute($fields); return (int) $this->pdo->lastInsertId(); } public function insertAttachment(int $inboxId, string $filename, string $subName, string $filePath): void { $stmt = $this->pdo->prepare(<<<SQL INSERT INTO Attachment (Inbox_id, Filename, SubName, FilePath) VALUES (:Inbox_id, :Filename, :SubName, :FilePath) SQL); $stmt->execute([ 'Inbox_id' => $inboxId, 'Filename' => $filename, 'SubName' => $subName, 'FilePath' => $filePath, ]); } } // --------------------------------------------------------------------------- // 主流程 / Main delivery workflow // --------------------------------------------------------------------------- final class MailDeliveryService { public function __construct( private readonly Config $config, private readonly PDO $pdo, private readonly MailRepository $repository, ) {} public function deliver(string $rawMail, string $recipient): void { if ($recipient === '' || !str_contains($recipient, '@')) { throw new InvalidArgumentException('Invalid recipient address.'); } require_once __DIR__ . '/phpQuery.php'; $parser = new HoyoMailParser($rawMail, $this->config->tmpPath); $this->repository->logRawMail($rawMail); $recipients = explode(',', $parser->header['to'] ?? ''); foreach ($recipients as $rawTo) { $this->deliverToSingleRecipient($rawMail, $parser, $rawTo); } } private function deliverToSingleRecipient(string $rawMail, HoyoMailParser $parser, string $rawTo): void { $toAddresses = mailparse_rfc822_parse_addresses($rawTo); $to = $toAddresses[0]['address'] ?? ''; $fromAddresses = mailparse_rfc822_parse_addresses($parser->header['from'] ?? ''); $fromEmail = $fromAddresses[0]['address'] ?? ''; $fromName = $fromAddresses[0]['display'] ?? ''; $body = $parser->body; if ($body->html === '') { $body->html = $body->plain; } else { $body->html = HtmlSanitiser::clean($body->html); } if ($body->plain === '') { $body->plain = nl2br(strip_tags($body->html), false); } $inboxId = $this->repository->insertInbox([ 'Source' => $rawMail, 'message_id' => $parser->header['message-id'] ?? '', 'To' => $to, 'From' => $parser->header['from'] ?? '', 'FromName' => $fromName, 'FromEmail' => $fromEmail, 'Subject' => $parser->header['subject'] ?? '', 'ContentTEXT' => $body->plain, 'ContentHTML' => $body->html, ]); foreach ($body->files as $attachment) { $savePath = $this->config->vmailPath . '/' . uniqid('', true); $this->repository->insertAttachment( inboxId: $inboxId, filename: $attachment->filename, subName: Helpers::extFileName($attachment->filename), filePath: $savePath, ); $bytes = base64_decode($attachment->base64Content, true); if ($bytes === false) { continue; } file_put_contents($savePath, $bytes); chmod($savePath, 0666); } } } // --------------------------------------------------------------------------- // 進入點 / Entry point // --------------------------------------------------------------------------- function main(array $argv): int { $config = Config::fromEnv(); try { $pdo = new PDO( $config->dsn(), $config->mysqlUsername, $config->mysqlPassword, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4', ], ); } catch (PDOException $e) { fwrite(STDERR, 'DB connection failed: ' . $e->getMessage() . PHP_EOL); return 1; } $recipient = $argv[1] ?? ''; $rawMail = stream_get_contents(STDIN) ?: ''; $service = new MailDeliveryService( config: $config, pdo: $pdo, repository: new MailRepository($pdo), ); try { $service->deliver($rawMail, $recipient); } catch (Throwable $e) { fwrite(STDERR, 'Delivery failed: ' . $e->getMessage() . PHP_EOL); return 1; } return 0; } exit(main($argv)); |
--
Hoyo 自己寫的解析程式
本來是用 MIME-mail-parser 這個別人寫的直接套,後來因為 X 和 XX 以及 XXX 種種的原因,在消音了無數次之後果斷自己寫
|
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 |
<?php mb_internal_encoding('UTF-8'); class HoyoMailParser { function __construct($a) { define( 'FilePath', '/tmp' ); $info = array(); $section = array(); $header = array(); $j = 0; $mail = mailparse_msg_create(); mailparse_msg_parse($mail, $a); $struct = mailparse_msg_get_structure($mail); //print_r($struct); foreach($struct as $st) { $section[] = mailparse_msg_get_part($mail, $st); } foreach( $section as $k=>$s ){ $info[] = mailparse_msg_get_part_data($s); } //print_r($info); // 信件 header $h = $info[0]['headers']; foreach( $h as $k=>$v ){ //echo $v ."---\r\n"; if ( is_string($v) ) $header[$k] = mb_decode_mimeheader($v); } $this->Header = $header; //print_r( $header ); for( $i=0; $i<count($struct) ;$i++ ){ // 接收 part data $GLOBALS["catchData"] = ''; mailparse_msg_extract_part($section[$i], $a, "catchData"); $tempData = $GLOBALS["catchData"]; // [transfer-encoding] => 8bit if ( $info[$i]['headers']['transfer-encoding'] =='8bit' ){ $tempData = mb_decode_mimeheader($tempData); } // 文字編碼轉換 if ( strtolower($info[$i]['charset']) !='utf-8' ){ $tempData = mb_convert_encoding( $tempData, "UTF-8", $info[$i]['charset'] ); } // HTML if ( preg_match('/text\/html/i', $info[$i]['headers']['content-type'] ) ){ $this->Body['HTML'] = $tempData; } // 純文字 if ( preg_match('/text\/plain/i', $info[$i]['headers']['content-type'] ) ){ $this->Body['Plain'] = $tempData; } // 檔案附件 if ( $info[$i]['headers']['x-attachment-id'] !='' ){ // 儲存檔案 $ta = explode('.', mb_decode_mimeheader($info[$i]['headers']['content-type']) ); $afs = trim( array_pop($ta), '"' ); file_put_contents( FilePath .'/'. $info[$i]['headers']['x-attachment-id'] .'.'. $afs , $tempData); // 是否是內嵌圖片 if ( preg_match('/inline/i', $info[$i]['headers']['content-disposition']) ){ $this->Body['HTML'] = str_replace('cid:'.$info[$i]['headers']['x-attachment-id'], 'data:'.$info[$i]['content-type'].';base64,'. base64_encode($GLOBALS["catchData"]), $this->Body['HTML']); $this->Body['File'][$j] = array( 'Filename'=> mb_decode_mimeheader($info[$i]['disposition-filename']), 'FileContent' => base64_encode($GLOBALS["catchData"]) ); $j++; } // 一般附件 if ( $info[$i]['content-disposition'] =='attachment' ) { $this->Body['File'][$j] = array( 'Filename'=> mb_decode_mimeheader($info[$i]['disposition-filename']), 'FileContent' => base64_encode($GLOBALS["catchData"]) ); $j++; } } } return $this; } } function catchData($part) { // 檔案大於 ?? 或多次執行直到結束 因此在此只要將資料拼接即可 $GLOBALS["catchData"] .= $part; } |
--
950 total views, 1 views today