phpmailer_init
云策文档标注
概述
phpmailer_init 是一个 WordPress 动作钩子,在 PHPMailer 实例初始化后触发,允许开发者自定义邮件发送设置。它通过 do_action_ref_array 调用,传递 PHPMailer 对象引用作为参数。
关键要点
- phpmailer_init 钩子在 PHPMailer 初始化后触发,用于修改邮件发送配置。
- 参数 $phpmailer 是 PHPMailer 实例的引用,可直接操作其属性。
- 该钩子使用 do_action_ref_array 调用,与 do_action 在参数传递方式上有所不同。
- 常用于配置 SMTP 连接、认证信息等,以替代默认的 PHP mail 函数。
代码示例
function my_phpmailer_example( $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.example.com';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 25;
$phpmailer->Username = 'yourusername';
$phpmailer->Password = 'yourpassword';
}
add_action( 'phpmailer_init', 'my_phpmailer_example' );注意事项
- 使用 $phpmailer->setFrom() 时,建议将第三个参数设为 false,以避免覆盖 Sender 头导致邮件被拒绝。
- 钩子参数传递方式:do_action_ref_array 将数组元素作为单独参数传递,而 do_action 传递整个数组。
原文内容
Fires after PHPMailer is initialized.
Parameters
$phpmailerPHPMailer-
The PHPMailer instance (passed by reference).
Source
do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
Changelog
| Version | Description |
|---|---|
| 2.2.0 | Introduced. |
Skip to note 3 content
Steven Lin
Example migrated from Codex:
This is an example of establishing an SMTP connection using the `
phpmailer_init` action:function my_phpmailer_example( $phpmailer ) { $phpmailer->isSMTP(); $phpmailer->Host = 'smtp.example.com'; $phpmailer->SMTPAuth = true; // Ask it to use authenticate using the Username and Password properties $phpmailer->Port = 25; $phpmailer->Username = 'yourusername'; $phpmailer->Password = 'yourpassword'; // Additional settings… //$phpmailer->SMTPSecure = 'tls'; // Choose 'ssl' for SMTPS on port 465, or 'tls' for SMTP+STARTTLS on port 25 or 587 //$phpmailer->From = "you@yourdomail.com"; //$phpmailer->FromName = "Your Name"; } add_action( 'phpmailer_init', 'my_phpmailer_example' );Skip to note 4 content
Ian Dunn
If you call
$phpmailer->setFrom(), it’s often important to explicitly set the third parameter tofalse, to tell PHPMailer to not override theSenderheader. The parameter defaults totrue, and using that can cause messages to be rejected.See #37736 for details.