WordPress SMTP邮箱服务配置相关排查记录

WordPress SMTP邮箱服务配置排查问题基础思路:

  1. 检查近期版本更新,是否有与邮箱相关的改动,重点关注。
  2. 命令行测试连接smtp服务器。
  3. 查看nginx、php、wordpress错误日志。
  4. 确保配置数据正确,尝试切换同一个备用stmp账号,切换服务商等。
  5. 开启wordpress调试模式,查看常规错误。
  6. 添加add_action,查看发送邮件错误。
  7. 添加单独测试邮件脚本。
  8. 待定查验:服务器IP被smtp服务商加入黑名单。长期商用,最好还是采购付费企业邮箱!

命令行测试连接smtp服务器

telnet smtp.gmail.com 587

看到类似下面的输出,表示连接成功:

Trying 74.125.68.109...
Connected to smtp.gmail.com.
Escape character is '^]'.
220 smtp.gmail.com ESMTP d123si1234567wmd.4 - gsmtp

如果出现Connected to ...并且收到以220开头的响应,说明连接成功。

确保配置数据正确

add_action('phpmailer_init', 'mail_smtp');

function mail_smtp( $phpmailer ) {

$phpmailer->FromName = 'XXXX'; // 发件人昵称

$phpmailer->Host = 'smtp.126.com'; // 邮箱SMTP服务器

$phpmailer->Port = 465; // SMTP端口,不需要改

$phpmailer->Username = 'xxxxxxxx@126.com'; // 邮箱账户

$phpmailer->Password = 'xxxxxxxxxxxxxxxxxxxx'; // 此处填写邮箱生成的授权码,不是邮箱登录密码

$phpmailer->From = 'xxxxxxxx@126.com'; // 收件邮箱账户

$phpmailer->SMTPAuth = true;

$phpmailer->SMTPSecure = 'ssl'; // 端口25时 留空,465时 ssl,不需要改

$phpmailer->IsSMTP();

}

添加add_action,查看发送邮件错误

add_action('wp_mail_failed', 'my_wp_mail_failed', 10, 1);

function my_wp_mail_failed($wp_error) {
    // 获取错误代码
    $error_code = $wp_error->get_error_code();
    
    // 获取错误消息
    $error_message = $wp_error->get_error_message();
    
    // 获取错误数据
    $error_data = $wp_error->get_error_data();

    // 记录详细错误信息
  //  error_log("邮件发送失败 - 代码: {$error_code}, 消息: {$error_message}, 数据: " . print_r($error_data, true));

    // 或者将详细信息写入自定义日志文件
    file_put_contents(
        WP_CONTENT_DIR . '/mail-error.log',
        "邮件发送失败 - 代码: {$error_code}, 消息: {$error_message}, 数据: " . print_r($error_data, true) . "\n",
        FILE_APPEND
    );
}

file_put_contents写入文件,可能需要权限,比较麻烦,也可以考虑临时写入数据库。

添加单独测试邮件脚本

带wordpress的版本:

<?php
// 加载WordPress环境
require_once('./wp-load.php');

// 设置错误报告(开发环境中)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 测试邮件信息
$to = 'xxxxxxx@qq.com'; // 替换为你要发送到的邮箱地址
$subject = 'Test Email from wp_mail() local';
$body = 'This is a test email sent using the wp_mail() function in WordPress.';
$headers = array('Content-Type: text/html; charset=UTF-8');

// 发送邮件
$mail_sent = wp_mail($to, $subject, $body, $headers);

if ($mail_sent) {
    echo 'Email was successfully sent!';
} else {
    echo 'Failed to send email.';
}

纯净版:

// 设置邮件内容
$to = "617887284@qq.com";
$subject = "Test mail from PHP local";
$message = "Hello! This is a test email.";
$headers = "From: sender@example.com";

// 发送邮件
if(mail($to, $subject, $message, $headers)) {
    echo "Mail sent successfully!";
} else {
    echo "Failed to send mail.";
}

(版权归cpury.com所有,转载请注明出处。)