php-simple-mail icon indicating copy to clipboard operation
php-simple-mail copied to clipboard

encodeUtf8Word() should prefer ASCII when possible

Open MircoBabin opened this issue 2 years ago • 0 comments

When sending an email only containing ASCII:

    require_once("./class.simple_mail.php");

    $from = '[email protected]';

    $email = new SimpleMail();
    $email->setFrom($from, 'Me')
        ->setParameters('-f'.$from)
        ->setReplyTo($from, '')
        ->setTo('[email protected]', 'Someone')
        ->setTo('[email protected]', 'Another one')
        ->setSubject('Subject')
        ->setMessage('Check your email.');
    $email->send();

I got the following error in my e-mail Inbox:

host mailfilter.hostnet.nl[91.184.19.251] said: 550
    Subject contains invalid characters. (in reply to end of DATA command)

So I changed the encodeUtf8Word() to:

    /**
     * encodeUtf8Word
     *
     * @param string $value The word to encode.
     *
     * @return string
     */
    public function encodeUtf8Word($value)
    {
        $isAscii = true;
        for ($i=0; $i<strlen($value); $i++) {
            $ch = ord(substr($value, $i, 1));
            if ($ch >= 128) {
                $isAscii = false;
                break;
            }
        }
        
        if ($isAscii) {
            return $value;
        } else {
            return sprintf('=?UTF-8?B?%s?=', base64_encode($value));
        }
    }

After this change, the email sends correctly, no error anymore.

So encodeUt8Word() should prefer plain ASCII, without encoding.

MircoBabin avatar Mar 11 '23 09:03 MircoBabin