I am sending an email to the client with csv attached file. While my actual file have few numbers with prefix 0. But when getting the attachment in the mail, those prefix is being removed. I don’t want those prefix to be removed. Attachment has to be as it is.
e.g:
number in actual csv: 002569854745
number in attached csv: 2569854745
here is my code
$myfile = __DIR__."/$filename"; $file_size = filesize($myfile); $handle = fopen($myfile, "r"); $content = fread($handle, $file_size); fclose($handle); $multipartSep = '-----'.md5(time()).'-----'; $headers = array( "From: from@gmail.com", "BCC: bcc@wcities.com", "Content-Type: multipart/mixed; boundary="$multipartSep"" ); $attachment = chunk_split(base64_encode($content)); $txt = "test mail"; $body = "--$multipartSeprn" . "Content-Type: text/plain; charset=ISO-8859-1; format=flowedrn" . "Content-Transfer-Encoding: 7bitrn" . "rn" . "$txtrn" . "--$multipartSeprn" . "Content-Type: text/csvrn" . "Content-Transfer-Encoding: base64rn" . "Content-Disposition: attachment; filename="$filename"rn" . "rn" . "$attachmentrn" . "--$multipartSep--"; //mail function
Advertisement
Answer
I’m doubtful that your CSV is being modified at all. I’d bet that if you inspected the raw file received, the zeroes would all be right there as they should be.
The problem will be in what happens next.
If you open a CSV with leading zeroes in something like Excel, it will treat the numbers as numbers and drop the leading zeroes. If you want to keep them, you need to format each value like "=""002569854745"""
. See this answer.
Another option in Excel is to ensure that when you import a CSV, you alter the import config so that it treats every field as text, rather than using its default “General” format, which applies automatic conversions like this.
If you’re not using Excel but something else, you’ll need to find out how to override these fields being interpreted as numbers.
Have you considered using PHPMailer that you tagged this question with?
I don’t see you checking encodings on the file content, and there’s no sign that you are actually performing the necessary steps to implement format=flowed
either, though nether of those are likely to do with this issue.