Complete website in Rs. 5,000 with Free Hosting & Domain. Offer ends in  00:00:00
Back to Blog

How to send Emails with WordPress wp_mail()

Quick guide on using wp_mail() with options

May 18, 2021 Updated: May 18, 2021

Simple Email

$to = 'sendto@example.com';
$subject = 'The subject';
$body = 'The email body content with <b>html</b> support.';
$headers = ['Content-Type: text/html; charset=UTF-8'];
if( !wp_mail($to, $subject, $body, $headers) ) {
    error_log('Email failed for: ' . $to . ' on ' . date('d-M-Y h:i:s a'));
}

Email with Cc and Bcc

$to = 'sendto@example.com';
$subject = 'The subject';
$body = 'The email body content with <b>html</b> support.';
$headers = [
    'Content-Type: text/html; charset=UTF-8',
    'Cc: anotheremail@example.com, myemail@example.com',
    'Bcc: myemail@example.com',
    ];
if( !wp_mail($to, $subject, $body, $headers) ) {
    error_log('Email failed for: ' . $to . ' on ' . date('d-M-Y h:i:s a'));
}

Email with Attachments

$tpl_dir = get_stylesheet_directory();
$attachments = [
    $tpl_dir . '/files/myfile.pdf',
    $tpl_dir . '/another-file.pdf',
    ];
$to = 'sendto@example.com';
$subject = 'The subject';
$body = 'The email body content with <b>html</b> support.';
$headers = ['Content-Type: text/html; charset=UTF-8'];
if( !wp_mail($to, $subject, $body, $headers, $attachments) ) {
    error_log('Email failed for: ' . $to . ' on ' . date('d-M-Y h:i:s a'));
}

Email with All Headers and multiple recipients

$to = 'sendto@example.com, myemail@example.com';
$subject = 'The subject';
$body = 'The email body content with <b>html</b> support.';
$headers = [
    'Content-Type: text/html; charset=UTF-8',
    'From: My Website <myemail@example.com>',
    'Reply-To: Person Name <personname@example.com>',
    'Cc: anotheremail@example.com, myemail@example.com',
    'Bcc: myemail@example.com',
    ];
if( !wp_mail($to, $subject, $body, $headers) ) {
    error_log('Email failed for: ' . $to . ' on ' . date('d-M-Y h:i:s a'));
}

Error Logging with wp_mail()

function log_wp_mail_errors( $wp_error ){
    $fn = getcwd() . '/wp_mail_errors.txt';
    $fp = fopen($fn, 'a');
    fputs($fp, 'wp_mail: ' . $wp_error->get_error_message() . PHP_EOL);
    fclose($fp);
}
add_action('wp_mail_failed', 'log_wp_mail_errors', 10, 1);
Contact

Got A Question For Us?

Feel free to ask anything directly on call or fill the form and we will contact back within few hours.