PHP邮件发送(使用SMTP)
发布时间:2024-02-21 10:14:56 所属栏目:PHP教程 来源:小徐写作
导读:在PHP中,你可以使用SMTP协议来发送邮件。下面是一个简单的示例代码,演示如何使用SMTP发送邮件:
```php
<?php
// 邮件发送的SMTP服务器地址
$smtpServer = 'smtp.example.com';
// SMTP服务器的端口号
```php
<?php
// 邮件发送的SMTP服务器地址
$smtpServer = 'smtp.example.com';
// SMTP服务器的端口号
在PHP中,你可以使用SMTP协议来发送邮件。下面是一个简单的示例代码,演示如何使用SMTP发送邮件: ```php <?php // 邮件发送的SMTP服务器地址 $smtpServer = 'smtp.example.com'; // SMTP服务器的端口号 $smtpPort = 587; // SMTP服务器的用户名 $smtpUsername = 'your-username'; // SMTP服务器的密码 $smtpPassword = 'your-password'; // 邮件的接收者邮箱地址 $to = 'recipient@example.com'; // 邮件的主题 $subject = '测试邮件'; // 邮件的内容 $body = '这是一封测试邮件的内容。'; // 创建一个SMTP客户端连接 $smtpConnection = fsockopen($smtpServer, $smtpPort, $errorNumber, $errorMessage); if (!$smtpConnection) { echo "无法连接到SMTP服务器:{$errorMessage}"; return; } // 读取SMTP服务器的响应 $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '220') { echo "无法连接到SMTP服务器:{$response}"; return; } // 发送SMTP认证命令 fwrite($smtpConnection, 'HELO ' . $smtpServer . "\r\n"); $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '250') { echo "SMTP认证失败:{$response}"; return; } // 发送用户名和密码进行认证 fwrite($smtpConnection, 'AUTH LOGIN\r\n'); $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '334') { echo "SMTP认证失败:{$response}"; return; } fwrite($smtpConnection, base64_encode($smtpUsername) . "\r\n"); $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '334') { echo "SMTP认证失败:{$response}"; return; } fwrite($smtpConnection, base64_encode($smtpPassword) . "\r\n"); $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '235') { echo "SMTP认证失败:{$response}"; return; } // 发送邮件的命令(包括接收者、主题、内容等) fwrite($smtpConnection, 'MAIL FROM: <' . $smtpUsername . '@' . $smtpServer . '>\r\n'); $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '250') { echo "发送邮件失败:{$response}"; return; } fwrite($smtpConnection, 'RCPT TO: <' . $to . '>\r\n'); $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '250') { echo "发送邮件失败:{$response}"; return; } fwrite($smtpConnection, 'DATA\r\n'); $response = fgets($smtpConnection, 1024); if (substr($response, 0, 3) !== '354') { echo "发送邮件失败:{$response}"; return; } (编辑:泰州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐