How to send emails using Arabic content via PHP mail function?

I am having trouble sending emails with Arabic content using the PHP mail function. Let's say I have this simple Arabic line:

بريد

I tried several ways to use headers, but the content of the email still ended up with something like: X*X1X(X1Y X/ . However, the email subject is correctly encoded if I use Arabic characters (thanks base64_encode, see Function below)

Here is one of the email features I tried

 function sendSimpleMail($to,$from,$subject,$message) { $headers = 'MIME-Version: 1.0' ."\r\n"; $headers .= 'To: '.$to ."\r\n"; $headers .= 'From: '.$from . "\r\n"; $headers .= 'Content-type: text/plain; charset=UTF-8; format=flowed' . "\r\n"; $headers .= 'Content-Transfer-Encoding: 8bit'."\r\n"; mail($to, '=?UTF-8?B?'.base64_encode($subject).'?=',$message, $headers); } 

Any suggestions on alternative ways to achieve this?

+4
source share
4 answers

Unfortunately, 8bit encoding is not reliable in email. Many mail agents will delete the upper bit of each byte in the message body. بريد - "\xD8\xA8\xD8\xB1\xD9\x8A\xD8\xAF" in bytes UTF-8; remove the top bit from these bytes and you get the ASCII "X(X1Y\nX/" .

The way to get non-ASCII characters in the message body is to set Content-Transfer-Encoding to base64 or quoted-printable , and encode the body using base64_encode or quoted_printable_encode respectively.

( quoted-printable better if mail is largely ASCII, as it retains readability in encoded form and is more efficient for ASCII. If all mail is Arabic, base64 is likely to be the best choice.)

+6
source
  $boundary = uniqid(rand(), true); $headers = "From: $from\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: multipart/alternative; boundary = $boundary\n"; $headers .= "This is a MIME encoded message.\n\n"; $headers .= "--$boundary\n" . "Content-Type: text/plain; charset=UTF-8 \n" . "Content-Transfer-Encoding: base64\n\n"; $headers .= chunk_split(base64_encode($plaintext)); $headers .= "--$boundary\n" . "Content-Type: text/html; charset=ISO-8859-1\n" . "Content-Transfer-Encoding: base64\n\n"; $headers .= chunk_split(base64_encode($msg)); $headers .= "--$boundary--\n" . mail($address, $subject, '', $headers); 

This works for me.

0
source

try it

 $headers .= 'From: =?UTF-8?B?'.base64_encode($from). "\r\n"; 
0
source

Your code works for me as it is.

Are you sure $message contains a valid UTF-8 string?

0
source

Source: https://habr.com/ru/post/1302376/


All Articles