RexArvind

Loading...

Back to Blog

How to send Emails with WordPress wp_mail()

May 18, 2021Updated: 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);


Place Ad Here




Contact me