以下是一个使用 SMTP 发送邮件的 PHP 类示例代码:

class SMTPMailer {
    private $host;
    private $port;
    private $username;
    private $password;
    
    public function __construct($host, $port, $username, $password) {
        $this->host = $host;
        $this->port = $port;
        $this->username = $username;
        $this->password = $password;
    }
    
    public function sendMail($to, $from, $subject, $body) {
        $headers = array(
            'MIME-Version: 1.0',
            'Content-type: text/html; charset=utf-8',
            'From: ' . $from,
            'Reply-To: ' . $from,
            'X-Mailer: PHP/' . phpversion()
        );
        
        $message = '<html><body>';
        $message .= '<h1>' . $subject . '</h1>';
        $message .= '<p>' . $body . '</p>';
        $message .= '</body></html>';
        
        $smtp = fsockopen($this->host, $this->port, $errno, $errstr, 10);
        
        if (!$smtp) {
            throw new Exception('SMTP connection failed: ' . $errstr);
        }
        
        $this->getResponse($smtp);
        
        fwrite($smtp, 'EHLO ' . $this->host . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, 'AUTH LOGIN' . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, base64_encode($this->username) . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, base64_encode($this->password) . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, 'MAIL FROM: <' . $this->username . '>' . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, 'RCPT TO: <' . $to . '>' . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, 'DATA' . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, 'Subject: ' . $subject . "\r\n");
        fwrite($smtp, implode("\r\n", $headers) . "\r\n");
        fwrite($smtp, "\r\n" . $message . "\r\n");
        fwrite($smtp, '.' . "\r\n");
        $this->getResponse($smtp);
        
        fwrite($smtp, 'QUIT' . "\r\n");
        $this->getResponse($smtp);
        
        fclose($smtp);
    }
    
    private function getResponse($smtp) {
        $response = '';
        while (substr($response, 3, 1) != ' ') {
            if (!($line = fgets($smtp, 256))) {
                throw new Exception('SMTP error: did not receive valid response from server');
            }
            $response .= $line;
        }
        return $response;
    }
}

// 使用示例:
$mailer = new SMTPMailer('smtp.example.com', 25, 'your-username', 'your-password');
$mailer->sendMail('to@example.com', 'from@example.com', 'Test Email', 'This is a test email.');

请注意,这只是一个简单的示例,具体的 SMTP 服务器设置和身份验证方法可能会有所不同。您需要根据您自己的 SMTP 服务器配置进行必要的修改。


原文地址: https://www.cveoy.top/t/topic/o0G8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录