Leave a Reply

5 comments

  1. from wp_mail codex page:

    The default content type is ‘text/plain’ which does not allow using HTML. However, you can set the content type of the email by using the ‘wp_mail_content_type’ filter.

    // In theme's functions.php or plug-in code:
    
    function wpse27856_set_content_type(){
        return "text/html";
    }
    add_filter( 'wp_mail_content_type','wpse27856_set_content_type' );
    
  2. As an alternative, you can specify the Content-Type HTTP header in the $headers parameter:

    $to = 'sendto@example.com';
    $subject = 'The subject';
    $body = 'The email body content';
    $headers = array('Content-Type: text/html; charset=UTF-8');
    
    wp_mail( $to, $subject, $body, $headers );
    
  3. Another easy way I’m going to share below. Even you can style your mail body as your wish. Maybe it’s helpful for you.

    $email_to = 'someaddress@gmail.com';
    $email_subject = 'Email subject';
    
    // <<<EOD it is PHP heredoc syntax
    $email_body = <<<EOD
    This is your new <b style="color: red; font-style: italic;">password</b> : {$password}
    EOD;
    
    $headers = ['Content-Type: text/html; charset=UTF-8'];
    
    $send_mail = wp_mail( $email_to, $email_subject, $email_body, $headers );
    

    More about PHP heredoc syntax https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

  4. Use ob_start, because this will allow you to use WP variables/functions like bloginfo etc.

    make a PHP file and paste your HTML in that file(use wp variables inside that php file if needed).

    Use the below code:

     $to = 'Email Address';
     $subject = 'Your Subject';
    
     ob_start();
     include(get_stylesheet_directory() . '/email-template.php');//Template File Path
     $body = ob_get_contents();
     ob_end_clean();
    
     $headers = array('Content-Type: text/html; charset=UTF-8','From: Test <test@test.com>');
     wp_mail( $to, $subject, $body, $headers );
    

    this will keep your code clean and due to ob_start we will also save the time of loading the file.