简体   繁体   中英

setting encoding for attachment in phpmailer

I am using phpmailer to send a monthly report.

It includes the € sign. Thus I need to set encoding to utf-8. I ran into a problem here.

Without encoding like this:

$mail->addStringAttachment($csvstring, $fileName);

the mail gets sent but in the attachment the € sign does not show up

when I try to add encoding:

$mail->addStringAttachment($csvstring, $fileName,  "utf-8", "text/csv");

The mail is sent but body and attachment are not present. I tried looking it up but there seems to be very little documentation.

Am I missing the obvious?

See: this line in PHPMailer's source code

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

If you want the CSV to be read as UTF-8 in programs that open it, add a BOM ( Byte Order Marker ; ie, "\\\\xef\\\\xbb\\\\xbf" ) to the string file contents.

"\\xef\\xbb\\xbf".$csvstring

UPDATE:

You can also do it like this.

$mail->addStringAttachment($csvstring, $fileName, "base64", "text/csv; charset=utf-8");

See also, the specs on MIME Content-Type , as it points out the proper way to set encoding; ie, text/csv; charset=utf-8 text/csv; charset=utf-8 .

You're getting confused. Encoding and CharSet are two different things. Generally the charset does not affect attachments because they are usually base-64 encoded, and thus are only 7-bit.

You can set an overall CharSet and an Encoding for your entire message, but you can override the overall encoding for each attachment.

The correct way to attach your content, as per the docs :

$mail->addStringAttachment($csvstring, $fileName, 'base64', 'text/csv');

With that pattern, the attachment will retain the exact binary content you pass into it - if you still have trouble with characters, it's a problem with the source data, not the sending that's causing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM