加入收藏 | 设为首页 | 会员中心 | 我要投稿 广西网 (https://www.guangxiwang.cn/)- 分布式数据库、建站、网络、内容创作、业务安全!
当前位置: 首页 > 教程 > 正文

PHP通过SMTP发送邮件的实现方法

发布时间:2024-11-25 14:30:14 所属栏目:教程 来源:DaWei
导读:   要使用PHP通过SMTP发送邮件,您需要使用PHP的内置邮件函数和SMTP服务器的相关信息。以下是一个简单的示例代码,演示如何使用PHP通过SMTP发送邮件:  ```php    // 邮件接收者信息

  要使用PHP通过SMTP发送邮件,您需要使用PHP的内置邮件函数和SMTP服务器的相关信息。以下是一个简单的示例代码,演示如何使用PHP通过SMTP发送邮件:

  ```php

  

  // 邮件接收者信息

  $to = 'recipient@example.com';

  // 发件人信息

  $from = 'sender@example.com';

  $fromName = 'Sender Name';

  // 邮件主题和内容

  $subject = 'Test Email';

  $message = 'This is a test email sent using PHP SMTP.';

  // SMTP服务器信息

2025AI目标图像,仅供参考

  $smtpServer = 'smtp.example.com';

  $smtpUsername = 'your_username';

  $smtpPassword = 'your_password';

  $smtpPort = 587; // SMTP端口号,通常为587或465

  $smtpSecure = 'tls'; // 加密方式,可以是'tls'或'ssl'

  // 创建邮件头部

  $headers = array(

  'From' => $from,

  'To' => $to,

  'Subject' => $subject,

  'MIME-Version' => '1.0',

  'Content-Type' => 'text/html; charset=UTF-8',

  'Reply-To' => $from

  );

  // 连接到SMTP服务器并发送邮件

  $smtpConnection = fsockopen($smtpServer, $smtpPort, $errorNumber, $errorMessage);

  if (!$smtpConnection) {

  echo "Error: Unable to connect to the SMTP server.";

  exit;

  }

  // 读取服务器返回的响应

  $serverResponse = fgets($smtpConnection, 1024);

  if (substr($serverResponse, 0, 3) !== '220') {

  echo "Error: Invalid response from the SMTP server.";

  exit;

  }

  // 发送EHLO命令,启用扩展功能

  $command = "EHLO " . $smtpServer . "\r\n";

  fwrite($smtpConnection, $command);

  $serverResponse = fgets($smtpConnection, 1024);

  if (substr($serverResponse, 0, 3) !== '250') {

  echo "Error: Invalid response from the SMTP server.";

  exit;

  }

  // 发送AUTH命令,启用身份验证功能

  $command = "AUTH LOGIN\r\n";

  fwrite($smtpConnection, $command);

  $serverResponse = fgets($smtpConnection, 1024);

  if (substr($serverResponse, 0, 3) !== '334') {

  echo "Error: Invalid response from the SMTP server.";

  exit;

  }

  // 发送用户名进行身份验证

  $command = base64_encode($smtpUsername) . "\r\n";

  fwrite($smtpConnection, $command);

  $serverResponse = fgets($smtpConnection, 1024);

  if (substr($serverResponse, 0, 3) !== '334') {

  echo "Error: Invalid response from the SMTP server.";

  exit;

  }

  // 发送密码进行身份验证

  $command = base64_encode($smtpPassword) . "\r\n";

  fwrite($smtpConnection, $command);

  $serverResponse = fgets($smtpConnection, 1024);

  if (substr($serverResponse, 0, 3) !== '235') {

  echo "Error: Invalid response from the SMTP server.";

  exit;

  }

  // 发送邮件内容,包括邮件头部和正文内容

  $command = "MAIL FROM: <" . $from . ">\r\n";

  fwrite($smtpConnection, $command);

(编辑:广西网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章