首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 郵件發送完整方案:Jmail 組件配置與原生 SMTP 類別實作

     編輯:PHP 綜合知識

方案一:Windows + Jmail 組件 (ASP/COM)

適用於 Windows Server 安裝 Jmail 服務的環境。

<%
Dim JMail
Set JMail = Server.CreateObject("JMail.Message")
JMail.Charset = "gb2312"
JMail.From = "webjxcom@163.com"
JMail.FromName = "網站管理員"
JMail.Subject = "郵件主題"
JMail.MailServerUserName = "webjx"
JMail.MailServerPassword = "webjx"
JMail.Priority = 1
JMail.AddHeader "Originating-IP", Request.ServerVariables("REMOTE_ADDR")
JMail.AddRecipient("5ss@163.com")
JMail.HTMLBody = "<html>...</html>"
JMail.Body = "純文字備用內容"
JMail.Send("smtp.163.com")
JMail.Close()
Set JMail = Nothing
%>

方案二:跨平台原生 PHP SMTP 類別

無需外部擴充,純 PHP 實現 SMTP 協議,支援驗證、HTML/純文、附件、抄送/密送。

<?php
class SmtpMailer {
    private $host, $port, $user, $pass, $from, $fromName;
    private $socket, $timeout = 30;

    public function __construct($host, $port=25, $user, $pass, $from, $fromName) {
        $this->host = $host; $this->port = $port;
        $this->user = $user; $this->pass = $pass;
        $this->from = $from; $this->fromName = $fromName;
    }

    public function send($to, $subject, $htmlBody, $textBody='', $cc='', $bcc='', $attachments=array()) {
        $this->connect();
        $this->auth();
        $this->mailFrom();
        $this->rcptTo(array_merge(explode(',', $to), explode(',', $cc), explode(',', $bcc)));
        $this->data($this->buildMessage($to, $subject, $htmlBody, $textBody, $cc, $bcc, $attachments));
        $this->quit();
        $this->disconnect();
    }

    // 內部方法:connect、auth(LOGIN)、mailFrom、rcptTo、data、buildMessage (MIME 組裝)、quit、disconnect
    // 完整程式碼請參考原文附件
}
?>

使用範例

<?php
require 'SmtpMailer.php';
$mailer = new SmtpMailer('smtp.163.com', 25, 'webjx', 'webjx', 'webjx@163.com', '網站管理員');
$mailer->send(
    'user@example.com',
    '測試主題',
    '<h1>HTML 內容</h1>',
    '純文字內容',
    'cc@example.com',
    'bcc@example.com',
    array('/path/to/file.pdf')
);

關鍵實作細節

  • MIME 多部分組裝:multipart/alternative 包裝 HTML+Text,multipart/mixed 掛載附件
  • Base64 編碼:附件內容、認證資訊均需 Base64
  • 回應碼檢查:每步 SMTP 指令檢查 2xx/3xx 回應
  • 超時與錯誤處理:fsockopen 設定 timeout、捕獲 socket 錯誤

現代最佳實踐建議

  1. 使用成熟庫:PHPMailer、Symfony Mailer、Laravel Mail
  2. 支援 SMTP over TLS/SSL(465/587 埠)
  3. 整合佇列系統(Redis/RabbitMQ)異步發送
  4. 使用專業郵件服務:SendGrid、Mailgun、Amazon SES、Postmark,提升送達率
  5. 實施 SPF/DKIM/DMARC 域名認證

常見問題排查

現象可能原因解決
連線逾時防火牆封鎖 25/465/587 埠開放埠口、改用 587 TLS
認證失敗帳密錯誤、未開啟 SMTP 服務確認郵箱設定、使用授權碼
進垃圾箱缺 SPF/DKIM、內容觸發規則配置域名認證、優化內容
中文亂碼編碼不一致統一 UTF-8、正確設定 Charset
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved