Skip to content

Instantly share code, notes, and snippets.

@frugan-dev
Last active October 16, 2018 11:14
Show Gist options
  • Save frugan-dev/6c4d22cd856456480bd77b988b5c9e80 to your computer and use it in GitHub Desktop.
Save frugan-dev/6c4d22cd856456480bd77b988b5c9e80 to your computer and use it in GitHub Desktop.
Wordpress action for multipart email with wp_mail function
{
"require": {
"soundasleep/html2text": "~0.3"
}
}
<?php
require __DIR__ . '/vendor/autoload.php';
add_action( 'phpmailer_init', 'phpmailer_init' );
//http://wordpress.stackexchange.com/a/191974
//http://stackoverflow.com/a/2564472
function phpmailer_init( $phpmailer )
{
if( $phpmailer->ContentType == 'text/html' ) {
$phpmailer->AltBody = Html2Text\Html2Text::convert( $phpmailer->Body );
}
}
@youri--
Copy link

youri-- commented Oct 16, 2018

Please see this gist: https://gist.github.com/youri--/c4618740b7c50c549314eaebc9f78661
It describes and fixes a huge problem when sending consecutive mails.

A simplified fix follows:

add_filter( 'wp_mail', 'force_phpmailer_reinit_for_multiple_mails', -1 );
function force_phpmailer_reinit_for_multiple_mails( $wp_mail_atts ) {
	global $phpmailer;

	if ( $phpmailer instanceof PHPMailer && $phpmailer->alternativeExists() ) {
		// AltBody property is set, so WordPress must already have used this
		// $phpmailer object just now to send mail, so let's
		// clear the AltBody property
		$phpmailer->AltBody = '';
	}

	// Return untouched atts
	return $wp_mail_atts;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment