Fix Plain Emails Sent as HTML
When a plugin switches all emails to HTML, WordPress's own plain emails arrive as one squashed paragraph with broken links; this adds line breaks and clickable links back.
Opens WPIDE on
Code
add_filter( 'wp_mail', function ( $atts ) {
$headers = is_array( $atts['headers'] ) ? implode( "\n", $atts['headers'] ) : (string) $atts['headers'];
$is_html = false !== stripos( $headers, 'text/html' ) || ( false === stripos( $headers, 'content-type' ) && 'text/html' === apply_filters( 'wp_mail_content_type', 'text/plain' ) );
$message = (string) $atts['message'];
$probe = preg_replace( '/<https?:[^>]+>/', '', $message );
if ( ! $is_html || $probe !== strip_tags( $probe ) ) {
return $atts;
}
$message = preg_replace( '/<(https?:[^>]+)>/', '$1', $message );
$atts['message'] = make_clickable( nl2br( esc_html( $message ) ) );
return $atts;
}, 15 );
Notes
Only touches emails sent as HTML whose body contains no HTML tags, such as the password reset and new user emails.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.