WordPress发布文章时群发邮件超300条无法发送问题排查
解决WordPress发布文章时仅发送部分订阅邮件的问题
嘿,你的核心逻辑没问题,但一次性给1000个订阅者发邮件会碰到几个常见的服务器限制,这就是为什么只有300封能成功发送的原因。我帮你拆解下问题,再给出靠谱的修复方案:
问题根源
- PHP执行超时:默认PHP的
max_execution_time一般在30-60秒,循环发1000封邮件的时间远远超过这个限制,脚本会被服务器强制终止,后面的邮件自然发不出去。 - 邮件服务器速率限制:大多数主机的邮件服务会限制单位时间内的发件数量(比如每分钟几十封),超过限制的邮件会被直接拒绝或者放入队列,但你的同步脚本不会等待队列处理完成。
- 同步发送的阻塞问题:
wp_mail()是同步执行的,每发一封都要等服务器响应,累计下来耗时太长,最终触发超时中断。
修复方案:改用异步分批次发送
最优解是把邮件发送拆分成多个小批次,用WordPress的Cron定时任务异步执行——这样既不会卡住发布文章的流程,也能避开超时和速率限制。
修改后的代码如下:
add_action( 'publish_post', 'wp_post_published_notification_schedule', 10, 2 ); function wp_post_published_notification_schedule( $ID, $post ) { $img = get_the_post_thumbnail( $ID, 'full' ); $link = get_permalink( $ID ); $title = $post->post_title; // 仅当标题和缩略图存在时触发任务 if ( $title && $img ) { // 避免重复触发任务 if ( ! wp_next_scheduled( 'wp_send_subscriber_notifications', array( $ID ) ) ) { wp_schedule_single_event( time(), 'wp_send_subscriber_notifications', array( $ID ) ); } } } // 定义异步发送邮件的钩子 add_action( 'wp_send_subscriber_notifications', 'wp_send_subscriber_notifications_batch' ); function wp_send_subscriber_notifications_batch( $post_id ) { global $wpdb; // 每次处理50封邮件,可根据服务器限制调整 $batch_size = 50; // 读取当前已处理的邮件数量 $processed_count = get_option( 'subscriber_notifications_processed_' . $post_id, 0 ); // 分页查询订阅者邮箱 $list_email = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `wp_es_emaillist` LIMIT %d OFFSET %d", $batch_size, $processed_count ) ); if ( empty( $list_email ) ) { // 所有邮件处理完成,清理记录 delete_option( 'subscriber_notifications_processed_' . $post_id ); return; } // 准备邮件内容 $post = get_post( $post_id ); $title = $post->post_title; $link = get_permalink( $post_id ); $img = get_the_post_thumbnail( $post_id, 'full' ); $content = "这里替换成你的邮件内容:<h3>新文章发布:{$title}</h3><p>{$img}</p><p>点击查看:<a href='{$link}'>{$link}</a></p>"; $subject = "新文章通知:{$title}"; $headers = array( 'Content-Type: text/html; charset=UTF-8' ); // 确保HTML格式 // 发送当前批次邮件 foreach ( $list_email as $email ) { // 注意:根据你的表结构调整邮箱字段名,比如$email->user_email wp_mail( $email->email, $subject, $content, $headers ); } // 更新已处理数量 $processed_count += $batch_size; update_option( 'subscriber_notifications_processed_' . $post_id, $processed_count ); // 延迟30秒执行下一批次,避开速率限制 wp_schedule_single_event( time() + 30, 'wp_send_subscriber_notifications', array( $post_id ) ); }
额外优化建议
- 调整批次和延迟:根据主机邮件服务器的限制修改
$batch_size和延迟时间(比如主机允许每分钟100封,就设$batch_size=100、延迟60秒)。 - 核对表字段:确认
wp_es_emaillist表中存储邮箱的字段名是email,如果不是,要修改代码里的$email->email为对应字段。 - 开启调试:如果仍有问题,开启WP_DEBUG查看错误日志,排查具体的发送失败原因。
- 用专业邮件服务:订阅量较大的话,建议搭配SendGrid、Mailgun这类服务+WP Mail SMTP插件,能大幅提升发送成功率和速率。
内容的提问来源于stack exchange,提问作者Said bouhmouch
相关产品推荐
相关产品推荐

