<?php

namespace Api\PhpUtils\Message;

class Email
{
    /**
     * @param string $from 发件人
     * @param string|array $to 收件人, 支持多个收件人
     * @param string $subject 邮件主题
     * @param string $body 邮件内容
     * @param string $smtp_server
     * @param int $smtp_port
     * @param string $content_type body内容的格式和编码, 可支持html格式邮件 $content_type="Content-Type: text/html; charset=\"utf-8\"\r\n\r\n"
     * @return bool
     */
    public static function sendMail($from, $to, $subject, $body, $smtp_server = 'smtp.yidian.com', $smtp_port = 25, $content_type = "Content-Type: text/plain; charset=\"utf-8\"\r\n\r\n")
    {
        if (empty($to)) {
            return false;
        }
        if (empty($from)) {
            $from = 'noreply@yidian-inc.com';
        }
        try {
            $email = explode('@', $from);
            $domain = $email[1];

            $sock = fsockopen($smtp_server, $smtp_port, $errno, $errstr, 1);

            fwrite($sock, "HELO " . $domain . "\r\n");
            fgets($sock);
            fwrite($sock, "MAIL FROM:<" . $from . ">\r\n");
            fgets($sock);
            if (!is_array($to)) {
                $to = [$to];
            }
            foreach ($to as $t) {
                fwrite($sock, "RCPT TO:<" . $t . ">\r\n");
            }
            fgets($sock);
            fwrite($sock, "DATA\r\n");
            fgets($sock);
            fwrite($sock, "Subject: " . $subject . "\r\n");
            fwrite($sock, "From: <" . $from . ">\r\n");
            foreach ($to as $t) {
                fwrite($sock, "To: <" . $t . ">\r\n");
            }
            fwrite($sock, $content_type);
            fwrite($sock, $body . "\r\n.\r\n");
            fgets($sock);
            fwrite($sock, "QUIT\r\n");
            fgets($sock);

            fclose($sock);
        } catch (\Exception $e) {
            return false;
        }
    }
}
