checker.php 2.85 KB
<?php
	require "./sendmail.php";

	$MAIL = "noreply@mail-ni-pon.net";
	$PASS = "NATkeSgdz86CuaA";
	$HOST = "imap.media-tek.conoha.io";
	$PORT = 143;

	$MATCHWORD = "「め~るNiポン」";
	run();

	function run()
	{
		global $MAIL, $PASS, $HOST, $PORT;

		if (($mbox = imap_open("{" . $HOST . ":" . $PORT . "/imap/notls}", $MAIL, $PASS)) == false) {
			echo "接続失敗";
		} else {
			// 未読
			$mail_id_list = imap_search($mbox, "UNFLAGGED");

			if ($mail_id_list) {
				foreach ($mail_id_list as $id) {
					if (!bounce_check($mbox, $id)) {
						// mail 送信
						$result = send_bounce_mail($mbox, $id);
						if ($result === true) {
							imap_setflag_full($mbox, $id,"\\Flagged");
						} else {
							echo $result; // console out exception
						}
					}
				}
			}

			// 3ヶ月以上経過したメールを削除
			$delete_mail_id_list = imap_search($mbox, '"BEFORE '. date('j-M-Y', strtotime('-3 month')) . '"');
			//$delete_mail_id_list = imap_search($mbox, "BEFORE 1 September 2019");
			var_dump($delete_mail_id_list);
			if ($delete_mail_id_list) {
				foreach ($delete_mail_id_list as $id) {
					// 処理したメールに削除フラグをセット
					echo 'delete ' . $id . "\n";
					imap_delete($mbox, $id);
				}
				imap_expunge($mbox);
			}
		}
	}

	function bounce_check($mbox, $id)
	{
		// header check
		$header = imap_headerinfo($mbox, $id);
		if (returnpath_check($header)) {
			return true;
		}
		// body check
		$body = get_body($mbox, $id);
		if (body_check($body)) {
			return true;
		}
		return false;
	}

	function returnpath_check($header)
	{
		// return path が空のものはbounce mail判定とする
		// return path を取得できなさそうなので、fromが MAILER DAEMON となっているものをbounce mail判定する
		$from = $header->from[0]->mailbox;
		if (mb_strtolower($from) === "mailer-daemon") {
			return false;
		} else {
			return true;
		}
	}

	function body_check($body)
	{
		global $MATCHWORD;
		if (mb_strpos($body, $MATCHWORD)) {
			echo 'match';
			// match
			return false;
		} else {
			return true;
		}
	}

	function get_body($mbox, $id)
	{
		$body = imap_body($mbox, $id, FT_INTERNAL);
		$body = imap_qprint($body);
		$body = str_replace('〜', '~', mb_convert_encoding($body, "UTF-8", "ISO-2022-JP"));
		//echo "\n";
		//global $MATCHWORD;
		//echo bin2hex($MATCHWORD);
		//echo "\n";
		//echo bin2hex($body); exit;
		return $body;
	}

	function send_bounce_mail($mbox, $id)
	{
		$body = get_body($mbox, $id);
		$to_mail = get_customer_admin_mail($body);

		$sendmail = new SendMail();
		$sendmail->to = $to_mail;
		$sendmail->body = $body;
		return $sendmail->send();
	}

	function get_customer_admin_mail($body)
	{
		preg_match("/「+[A-Za-z0-9\-\.\_]+@[A-Za-z0-9\-\_]+\.[A-Za-z0-9\-\.\_]+」/", $body, $mail_list);
		$mail = $mail_list[0];
		$mail = ltrim($mail, "「");
		$mail = rtrim($mail, "」");
		return $mail;
	}