Using WordPress ‘phpmailer_init’ PHP action

The phpmailer_init WordPress action fires after PHPMailer is initialized, allowing you to modify its settings.

Usage

add_action('phpmailer_init', 'your_custom_function');

function your_custom_function($phpmailer) {
  // Your custom code here
  return $phpmailer;
}

Parameters

  • $phpmailer (PHPMailer) – The PHPMailer instance, passed by reference.

More information

See WordPress Developer Resources: phpmailer_init

Examples

Set the default sender name and email address

Change the default sender name and email address for all outgoing emails.

add_action('phpmailer_init', 'set_default_sender');

function set_default_sender($phpmailer) {
  $phpmailer->setFrom('[email protected]', 'Example Site');
}

Use SMTP for email delivery

Configure PHPMailer to use SMTP for email delivery.

add_action('phpmailer_init', 'use_smtp_for_email_delivery');

function use_smtp_for_email_delivery($phpmailer) {
  $phpmailer->isSMTP();
  $phpmailer->Host = 'smtp.example.com';
  $phpmailer->Port = 587;
  $phpmailer->SMTPAuth = true;
  $phpmailer->Username = 'your_username';
  $phpmailer->Password = 'your_password';
}

Enable HTML content in emails

Enable HTML content for outgoing emails.

add_action('phpmailer_init', 'enable_html_content_in_emails');

function enable_html_content_in_emails($phpmailer) {
  $phpmailer->isHTML(true);
}

Add a custom header to emails

Add a custom header to all outgoing emails.

add_action('phpmailer_init', 'add_custom_email_header');

function add_custom_email_header($phpmailer) {
  $phpmailer->addCustomHeader('X-Custom-Header', 'your-custom-value');
}

Change email charset

Change the charset used for outgoing emails.

add_action('phpmailer_init', 'change_email_charset');

function change_email_charset($phpmailer) {
  $phpmailer->CharSet = 'UTF-8';
}