PHP Mailer UTF-8 Encoding problems

Zsolt Bíró picture Zsolt Bíró · Jul 22, 2015 · Viewed 15.6k times · Source

I've been working on a website recently and decided to include a PHPMailer on it. The problem is I'm hungarian and the site is fully in hungarian too so I had to use UTF-8 charset. The PHP mailer I decided to use is not yet capable of using UTF-8 and I cant figure out how to make it echo things in my prefered charset. Please help!

<?php

require_once('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();

if( isset( $_POST['template-contactform-submit'] ) AND $_POST['template-contactform-submit'] == 'submit' ) {
    if( $_POST['template-contactform-name'] != '' AND $_POST['template-contactform-email'] != '' AND $_POST['template-contactform-message'] != '' ) {

        $name = $_POST['template-contactform-name'];
        $email = $_POST['template-contactform-email'];
        $phone = $_POST['template-contactform-phone'];
        $service = $_POST['template-contactform-service'];
        $subject = $_POST['template-contactform-subject'];
        $message = $_POST['template-contactform-message'];

        $subject = isset($subject) ? $subject : 'New Message From Contact Form';

        $botcheck = $_POST['template-contactform-botcheck'];

        $toemail = ''; // Your Email Address
        $toname = ''; // Your Name

        if( $botcheck == '' ) {

            $mail->SetFrom( $email , $name );
            $mail->AddReplyTo( $email , $name );
            $mail->AddAddress( $toemail , $toname );
            $mail->Subject = $subject;

            $name = isset($name) ? "Név: $name<br>" : '';
            $email = isset($email) ? "E-mail: $email<br><br>" : '';
            $message = isset($message) ? "Üzenet: $message<br>" : '';

            $referrer = $_SERVER['HTTP_REFERER'] ? '<br><br><br>Az üzenetet továbbította: ' . $_SERVER['HTTP_REFERER'] :'';

            $body = "$name $email $message $referrer";

            $mail->MsgHTML( $body );

            $mail->CharSet="UTF-8";

            $sendEmail = $mail->Send();

            if( $sendEmail == true ):
                echo 'Üzenet elküldve!';
            else:
                echo 'Üzenetküldés sikertelen. Kérlek próbáld újra!' . $mail->ErrorInfo . '';
            endif;
        } else {
            echo 'Bot vagy. Kérlek próbálkozz újra!';
        }
    } else {
        echo 'Kérlek tölts ki minden mezőt és próbáld meg újra!';
    }
} else {
    echo 'Valami félrecsúszott. Kérlek próbáld meg mégegyszer.';
}

?>

Answer

Wesley picture Wesley · Jan 24, 2017

Try replace:

$mail->CharSet="UTF-8";

by:

$mail->CharSet = 'UTF-8';

It's working perfectly here.