The correct way is to apply a filter to wp_mail_from and wp_mail_from_name. You would think that using the $headers would work and normally it would but there are many plugins that filter and then don’t take off their filter when they have sent their email which then leaves those details on the email for the next send. Below is a snippet of my plugin that uses these filters. Adjust code to your liking. Take note how I remove the filters once I’ve sent the mail via wp_mail()
:
public function send_notify_email($alertMessage) {
$options = get_option(self::$settings_option_field); // Get settings
$subject = sprintf(__("WordPress File Monitor Plus: Alert (%s)", "wordpress-file-monitor-plus"), site_url()); // build subject
$subject = apply_filters("sc_wpfmp_format_email_subject", $subject); // allow filter to alter subject
add_filter('wp_mail_from', array(__CLASS__, 'sc_wpfmp_wp_mail_from')); // add filter to modify the mail from
add_filter('wp_mail_from_name', array(__CLASS__, 'sc_wpfmp_wp_mail_from_name')); // add filter to modify the mail from name
add_filter('wp_mail_content_type', array(__CLASS__, 'sc_wpfmp_wp_mail_content_type')); // add filter to modify the mail content type
wp_mail($options['notify_address'], $subject, $alertMessage); // send mail
remove_filter('wp_mail_from', array(__CLASS__, 'sc_wpfmp_wp_mail_from')); // remove applied filter
remove_filter('wp_mail_from_name', array(__CLASS__, 'sc_wpfmp_wp_mail_from_name')); // remove applied filter
remove_filter('wp_mail_content_type', array(__CLASS__, 'sc_wpfmp_wp_mail_content_type')); // remove applied filter
}
/**
* Set from address for email notification
*
* @return void
*/
public function sc_wpfmp_wp_mail_from() {
$options = get_option(self::$settings_option_field); // Get settings
return $options['from_address']; // Return the from address
}
/**
* Set from name for email notification
*
* @return string $from_name
*/
public function sc_wpfmp_wp_mail_from_name() {
$from_name = __("WordPress File Monitor Plus", "wordpress-file-monitor-plus");
$from_name = apply_filters("sc_wpfmp_format_email_from_name", $from_name); // allow filter to alter the from name
return $from_name; // return from name
}
/**
* Set content type for email notification
*
* @return string
*/
public function sc_wpfmp_wp_mail_content_type() { return "text/html"; }