纯代码实现 SMTP 邮件系统

Ginc
Ginc
Ginc
管理员
79
文章
0
粉丝
建站开发评论237阅读模式
前言 昨天收到热心网友的反馈提醒,本站邮箱系统会出现一个邮件发两送两次的情况。今天下班回家经过测试发现是主题跟Easy WP SMTP 插件互相影响所致。索性删掉SMTP插件,以纯代码形式实现。

由于网络上很多同类型教程,所以如有雷同,纯属巧合。

1、说明

由于wordpress主题在更新是会更新主题文件,所以,为防止邮箱配置在更新主题时被刷新,本文邮件系统实现方式为独立文件。文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

文件保存位置文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

inc/smtp-mail/   //在主题子主题目录下新建一个 smtp-mail 文件夹

 文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

2、整体架构

你的主题/
├── functions.php          ← 只加一行引入代码
└── inc/
    └── smtp-mail/
        ├── config.php       ← SMTP 配置
        ├── template.php     ← HTML 邮件模板
        ├── notify-admin.php ← 评论通知站长
        ├── notify-user.php  ← 回复通知评论者
        └── test.php         ← 测试工具   //可以不用

 文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

3、系统引入

在主题文件functions.php中添加以下代码文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

/* ============================================
   SMTP 邮件系统引入
   ============================================ */
$smtp_mail_dir = get_stylesheet_directory() . '/inc/smtp-mail/';

require_once $smtp_mail_dir . 'config.php';
require_once $smtp_mail_dir . 'template.php';
require_once $smtp_mail_dir . 'notify-admin.php';
require_once $smtp_mail_dir . 'notify-user.php';
require_once $smtp_mail_dir . 'test.php';  // 这个可以不用

 文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

4、配置文件

在邮件系统文件夹下新建config.php文件,并添加以下代码文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

<?php
/**
 * SMTP 邮件服务器配置
 */

add_action('phpmailer_init', 'custom_smtp_config');
function custom_smtp_config($phpmailer) {
    $phpmailer->isSMTP();
    $phpmailer->Host       = 'smtp.qq.com';
    $phpmailer->SMTPAuth   = true;
    $phpmailer->Port       = 465;
    $phpmailer->Username   = 'your_email@qq.com';
    $phpmailer->Password   = 'your_smtp_authorization_code';
    $phpmailer->SMTPSecure = 'ssl';
    $phpmailer->From       = 'your_email@qq.com';
    $phpmailer->FromName   = get_bloginfo('name');
    $phpmailer->CharSet    = 'UTF-8';
}

以上配置信息请按需修改文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

 文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

5、邮件模板

在邮件系统文件夹下新建template.php文件,并添加以下代码文章源自今夕何夕兮-https://www.ginc.site/building-and-development1428.html

<?php
/**
 * HTML 邮件模板
 */

function custom_email_template($title, $content, $footer = '') {
    $site_name = get_bloginfo('name');
    $site_url  = home_url();
    $year      = date('Y');

    if (empty($footer)) {
        $footer = "此邮件由 {$site_name} 系统自动发送,请勿直接回复。";
    }

    return '
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>' . esc_html($title) . '</title>
    </head>
    <body style="margin:0; padding:0; background-color:#f0f2f5; font-family:\'Helvetica Neue\',Arial,\'PingFang SC\',\'Microsoft YaHei\',sans-serif;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f0f2f5; padding:40px 0;">
            <tr>
                <td align="center">
                    <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="background-color:#ffffff; border-radius:16px; overflow:hidden; box-shadow:0 4px 24px rgba(0,0,0,0.08);">
                        <tr>
                            <td style="height:6px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);"></td>
                        </tr>
                        <tr>
                            <td style="padding:36px 48px 0 48px;">
                                <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td style="font-size:22px; font-weight:700; color:#1a1a2e; letter-spacing:-0.5px;">
                                            ' . esc_html($site_name) . '
                                        </td>
                                        <td align="right" style="font-size:13px; color:#999;">
                                            ' . date('Y年m月d日 H:i') . '
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding:20px 48px 0 48px;">
                                <div style="height:1px; background:linear-gradient(90deg, transparent, #e8e8e8, transparent);"></div>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding:28px 48px 0 48px;">
                                <h1 style="margin:0; font-size:20px; font-weight:600; color:#1a1a2e; line-height:1.4;">
                                    ' . $title . '
                                </h1>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding:20px 48px 0 48px;">
                                <div style="font-size:15px; line-height:1.8; color:#444;">
                                    ' . $content . '
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding:32px 48px 0 48px;">
                                <div style="height:1px; background:linear-gradient(90deg, transparent, #e8e8e8, transparent);"></div>
                            </td>
                        </tr>
                        <tr>
                            <td style="padding:24px 48px 36px 48px;">
                                <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td style="font-size:12px; color:#aaa; line-height:1.6;">
                                            ' . esc_html($footer) . '
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="padding-top:12px; font-size:12px; color:#ccc;">
                                            &copy; ' . $year . ' ' . esc_html($site_name) . ' &middot;
                                            <a href="' . $site_url . '" style="color:#667eea; text-decoration:none;">' . $site_url . '</a>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                    <table role="presentation" width="600" cellpadding="0" cellspacing="0">
                        <tr>
                            <td style="padding:20px 0; text-align:center; font-size:11px; color:#bbb;">
                                本邮件由系统自动发送
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </body>
    </html>';
}

 

6、通知邮件模板

 

6.1新评论

在邮件系统文件夹下新建 notify-admin.php ,并添加以下代码

<?php
/**
 * 新评论
 */

add_action('comment_post', 'notify_admin_new_comment', 10, 3);
function notify_admin_new_comment($comment_id, $comment_approved, $commentdata) {
    $admin_email = get_option('admin_email');
    if ($commentdata['comment_author_email'] === $admin_email) {
        return;
    }
    if ($comment_approved === 'spam') {
        return;
    }

    $post_title   = get_the_title($commentdata['comment_post_ID']);
    $post_link    = get_permalink($commentdata['comment_post_ID']);
    $author       = $commentdata['comment_author'];
    $author_email = $commentdata['comment_author_email'];
    $content      = $commentdata['comment_content'];
    $status_text  = $comment_approved ? '已自动审核通过' : '正在等待审核';

    $inner = '';

    // 文章信息卡片
    $inner .= '<div style="background:#f8f9fb; border-radius:10px; padding:20px 24px; margin-bottom:20px; border-left:4px solid #667eea;">';
    $inner .= '<div style="font-size:13px; color:#888; margin-bottom:6px;">评论文章</div>';
    $inner .= '<a href="' . esc_url($post_link) . '" style="font-size:16px; font-weight:600; color:#1a1a2e; text-decoration:none;">' . esc_html($post_title) . '</a>';
    $inner .= '</div>';

    // 评论者信息
    $inner .= '<div style="margin-bottom:20px;">';
    $inner .= '<table role="presentation" cellpadding="0" cellspacing="0" style="font-size:14px; color:#555;">';
    $inner .= '<tr><td style="padding:4px 16px 4px 0; color:#999; white-space:nowrap;">昵称</td><td style="padding:4px 0;"><strong>' . esc_html($author) . '</strong></td></tr>';
    $inner .= '<tr><td style="padding:4px 16px 4px 0; color:#999; white-space:nowrap;">邮箱</td><td style="padding:4px 0;">' . esc_html($author_email) . '</td></tr>';
    $inner .= '<tr><td style="padding:4px 16px 4px 0; color:#999; white-space:nowrap;">状态</td><td style="padding:4px 0;"><span style="display:inline-block; padding:2px 10px; border-radius:20px; font-size:12px; background:' . ($comment_approved ? '#e8f5e9' : '#fff3e0') . '; color:' . ($comment_approved ? '#2e7d32' : '#ef6c00') . ';">' . $status_text . '</span></td></tr>';
    $inner .= '</table>';
    $inner .= '</div>';

    // 评论内容
    $inner .= '<div style="background:#fafbfc; border-radius:10px; padding:20px 24px; border:1px solid #eee; margin-bottom:24px;">';
    $inner .= '<div style="font-size:13px; color:#888; margin-bottom:10px;">评论内容</div>';
    $inner .= '<div style="font-size:15px; line-height:1.8; color:#333;">' . nl2br(esc_html($content)) . '</div>';
    $inner .= '</div>';

    // 操作按钮
    $inner .= '<table role="presentation" cellpadding="0" cellspacing="0"><tr>';
    $inner .= '<td style="padding-right:12px;"><a href="' . admin_url('edit-comments.php') . '" style="display:inline-block; padding:10px 24px; background:#667eea; color:#fff; border-radius:8px; font-size:14px; font-weight:500; text-decoration:none;">管理评论</a></td>';
    $inner .= '<td><a href="' . esc_url($post_link) . '#comment-' . $comment_id . '" style="display:inline-block; padding:10px 24px; background:#f0f2f5; color:#555; border-radius:8px; font-size:14px; font-weight:500; text-decoration:none;">查看评论</a></td>';
    $inner .= '</tr></table>';

    $subject = '💬 新评论通知:' . $author . ' 评论了「' . $post_title . '」';
    $message = custom_email_template('📝 收到新评论', $inner);
    $headers = ['Content-Type: text/html; charset=UTF-8'];

    wp_mail($admin_email, $subject, $message, $headers);
}

 

6.2回复通知

在邮件系统文件夹下新建 notify-user.php  ,并添加以下代码

<?php
/**
 * 回复通知
 */

add_action('comment_post', 'notify_commenter_on_reply', 10, 3);
function notify_commenter_on_reply($comment_id, $comment_approved, $commentdata) {
    $parent_id = $commentdata['comment_parent'];
    if (!$parent_id) {
        return;
    }

    $parent_comment = get_comment($parent_id);
    if (!$parent_comment) {
        return;
    }

    $admin_email    = get_option('admin_email');
    $replier_email  = $commentdata['comment_author_email'];
    $is_admin_reply = ($replier_email === $admin_email);

    if (!$is_admin_reply) {
        return;
    }

    $recipient_email = $parent_comment->comment_author_email;
    if (empty($recipient_email) || $recipient_email === $admin_email) {
        return;
    }

    $post_title     = get_the_title($commentdata['comment_post_ID']);
    $post_link      = get_permalink($commentdata['comment_post_ID']);
    $parent_name    = $parent_comment->comment_author;
    $parent_content = $parent_comment->comment_content;
    $reply_content  = $commentdata['comment_content'];
    $replier_name   = $commentdata['comment_author'];

    $inner = '';

    $inner .= '<p style="margin:0 0 20px 0;">Hi <strong>' . esc_html($parent_name) . '</strong>,您在「' . esc_html($post_title) . '」下的评论收到了回复:</p>';

    // 原评论
    $inner .= '<div style="background:#f8f9fb; border-radius:10px; padding:18px 22px; margin-bottom:16px; border-left:4px solid #ccc;">';
    $inner .= '<div style="font-size:12px; color:#999; margin-bottom:8px;">您的评论</div>';
    $inner .= '<div style="font-size:14px; line-height:1.7; color:#666; font-style:italic;">"' . esc_html(mb_substr($parent_content, 0, 200)) . (mb_strlen($parent_content) > 200 ? '...' : '') . '"</div>';
    $inner .= '</div>';

    // 站长回复
    $inner .= '<div style="background:#f0f0ff; border-radius:10px; padding:18px 22px; margin-bottom:24px; border-left:4px solid #667eea;">';
    $inner .= '<div style="font-size:12px; color:#667eea; margin-bottom:8px; font-weight:600;">' . esc_html($replier_name) . ' 的回复</div>';
    $inner .= '<div style="font-size:15px; line-height:1.8; color:#333;">' . nl2br(esc_html($reply_content)) . '</div>';
    $inner .= '</div>';

    // 按钮
    $inner .= '<table role="presentation" cellpadding="0" cellspacing="0"><tr>';
    $inner .= '<td><a href="' . esc_url($post_link) . '#comment-' . $comment_id . '" style="display:inline-block; padding:12px 32px; background:#667eea; color:#fff; border-radius:8px; font-size:14px; font-weight:500; text-decoration:none;">查看回复详情</a></td>';
    $inner .= '</tr></table>';

    $inner .= '<p style="margin:24px 0 0 0; font-size:13px; color:#999;">如需继续交流,欢迎回到文章页面参与讨论。</p>';

    $subject = '💬 ' . $replier_name . ' 回复了您的评论 - ' . $post_title;
    $message = custom_email_template('💬 收到回复', $inner);
    $headers = ['Content-Type: text/html; charset=UTF-8'];

    wp_mail($recipient_email, $subject, $message, $headers);
}

 

7、连接测试[可忽略]

在邮件系统文件夹下新建 test.php,并添加以下代码

<?php
/**
 * SMTP 连接测试
 * 访问: 你的域名/?test_smtp=1(需管理员登录)
 */

add_action('init', 'test_smtp_connection');
function test_smtp_connection() {
    if (!isset($_GET['test_smtp']) || !current_user_can('manage_options')) {
        return;
    }

    $to      = get_option('admin_email');
    $subject = '✅ SMTP 测试邮件 - ' . get_bloginfo('name');
    $inner   = '<p>恭喜!您的 WordPress SMTP 邮件配置已成功。</p>';
    $inner  .= '<p style="color:#999; font-size:13px;">发送时间:' . current_time('Y-m-d H:i:s') . '</p>';
    $message = custom_email_template('SMTP 连接测试', $inner);
    $headers = ['Content-Type: text/html; charset=UTF-8'];

    $result = wp_mail($to, $subject, $message, $headers);

    if ($result) {
        wp_die('✅ 测试邮件已成功发送至 ' . $to . ',请检查收件箱。', '发送成功');
    } else {
        wp_die('❌ 邮件发送失败,请检查 SMTP 配置。', '发送失败');
    }
}

 

以上,就是纯代码实现 SMTP 邮件系统的所有文件,此方法functions.php 始终只保留那几行 require_once,保持干净。后续要改哪个功能直接改对应文件就行,互不影响。

 

特别鸣谢:热衷于的博客   感谢这个热心网友的反馈。

除特别声明外,本站内容遵循 CC BY-NC-ND 4.0协议。转载请注明出处。

weinxin
提示:
部分资源收集于网络,只做学习和交流使用,版权归原作者所有。
 
Ginc
  • 本文由 Ginc 发表于2026年8月15日
  • 转载请保留本文链接:纯代码实现 SMTP 邮件系统:https://www.ginc.site/building-and-development1428.html
匿名

发表评论

匿名网友
确定

拖动滑块以完成验证