Set “Envelope-From” header for wp_mail() - Cobbled Code

WordPress emails were not being sent out by the server. But why?
In this case the site is hosted by Goneo.
As it appears Goneo requires:

  1. Emails to be sent from an address registered with them
  2. The ‘Envelope-From’ email header set to that address

It’s not a bug, it’s a feature!

Set the thing…

WordPress sends its emails via the wp_mail() function. In turn, this function uses the PHPMailer library to generate and send the actual email. Just before sending the mail, wp_mail() calls the helpful phpmailer_init action which gives us access to the PHPMailer instance. This is where we can use the setfrom() method to set the Envelope From header:

add_action( 'phpmailer_init', 'prefix_add_phpmailer_setfrom' );

/**
 * Add setFrom for hosts that insist on making life hard.
 *
 * @param array $phpmailer The PHPMailer instance, passed by reference.
 */
function prefix_add_phpmailer_setfrom( $phpmailer ) {

	$phpmailer->setFrom(
		get_option( 'admin_email' ), // From email address.
		'WordPress' // From name.
	);
}

Rejoice!

Leave a Reply

Your email address will not be published. Required fields are marked *