如何在电子邮件标题中编码空格?

I want to send an e-mail using the mail-function in PHP. The "FROM"-part of the header should contain a name with a space

 name with space <mail@server.tld>

Unfortunately, some mail clients cannot handle the spaces. Thats why e.g. Thunderbird adds quotes to the name.

 "name with space" <mail@server.tld>

That works fine, until you add special characters like ÄÖÜ, since they need to be encoded. The follwing would not work:

 "name with ÄÖÜ and space" <mail@server.tld>

Thats why I tried the function mb_encode_mimeheader

echo mb_encode_mimeheader("name with"." ÄÖÜ"." and space", "ISO-8859-1", "Q");
# result:
# name with =?ISO-8859-1?Q?=C3=84=C3=96=C3=9C=20and=20space?=

That still does not work, since before the first occurence of the special characters, the spaces are still in the string. the correct result schould be:

=?ISO-8859-1?Q?name=20with=20=C3=84=C3=96=C3=9C=20and=20space?=

Is there a function in PHP that can handle this? or should I use a mixture of quotes and ´mb_encode_mimeheader´? Or is there a different way to handle spaces in mailheaders? To be honest, I did not understand the meaning of the different whitespaces mentioned in the RFC822.

You don't need quotes. RFC2047-encoding (i.e. mb_encode) handles spaces as well.

(Although for the record, just plain spaces are completely unproblematic; they are not the reason some clients use quoting, which is often completely redundant anyway. So the result with the spaces is actually not incorrect at all.)

As IETF says, emails only let ASCII characters in their headers. Thus I guess you should ASCII encode your email header.

However, based on the trends that I see in new specifications coming from Internet Engineering Task Force, soon we should see that you might don't need to encode/decode your headers.