问题
WordPress 默认使用 mail() 发送邮件,经常被服务器拒绝或进入垃圾箱。生产环境应改为 SMTP,并定制通知模板。
一、SMTP 配置
推荐使用 WP Mail SMTP 插件,或在子主题 functions.php 中直接配置:
Text
add_action('phpmailer_init', function ($phpmailer) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.qq.com';
$phpmailer->SMTPAuth = true;
$phpmailer->Username = 'your@qq.com';
$phpmailer->Password = 'auth-code';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Port = 465;
$phpmailer->From = 'your@qq.com';
$phpmailer->FromName = get_bloginfo('name');
});
二、邮件模板定制
通过过滤器替换默认邮件内容,输出带样式的 HTML 模板:
Text
add_filter('wp_mail_content_type', function () { return 'text/html'; });
add_filter('wp_mail', function ($args) {
$args['message'] = '' . $args['message'] . '';
return $args;
});
三、按事件定制邮件
如新用户注册欢迎邮件:
Text
add_action('user_register', function ($uid) {
$user = get_userdata($uid);
wp_mail($user->user_email, '欢迎注册', '感谢加入 ' . get_bloginfo('name') . '!');
});
注意事项
- SMTP 密码使用授权码而非邮箱登录密码。
- 发送量大的站点应接入队列,避免请求阻塞。

