PHP mail function - attachment coming as text - php

I know there are lot posts related to PHP mail function. But seriously i couldn't figure out what's wrong with my code below:
$subject = "New article submitted.";
$message = "You've received this e-mail through your website's write an article form: \n";
$message .= "Name: {$data['username']} \n";
$message .= "E-mail: {$data['email']} \n";
$message .= "\nRegards,\nAakriti \n";
$headers = "From: {$data['name']} <{$data['email']}> \n";
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the plain message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain;\n charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n" .
"--{$mime_boundary}\n";
// preparing attachments
for($i=0;$i < count($_FILES['articledata']['name']); $i++) {
// store the file information to variables for easier access
$tmp_name = $_FILES['articledata']['tmp_name'][$i];
$type = $_FILES['articledata']['type'][$i];
$name = $_FILES['articledata']['name'][$i];
$size = $_FILES['articledata']['size'][$i];
$file = fopen($tmp_name,"rb");
$attachment = fread($file,filesize($tmp_name));
fclose($file);
$attachment = chunk_split(base64_encode($attachment));
print_r($attachment);
//$attachment = chunk_split(base64_encode(file_get_contents($tmp_name)));
$message .= "Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$name}\"\n\n" .
$attachment . "\n" .
"--{$mime_boundary}\n";
$message .= "--\n\n";
}
$headers .= "Reply-To: <{$data['email']}>";
if (mail($recipient,$subject,$message,$headers)) {
echo "<p>Thank you! Your mail was successfully sent to the webmaster. Thank you for your time.</p>";
} else {
echo "<p>Sorry, there was an error and your mail was not sent. Please find an alternative method of contacting the webmaster.</p>";
}
It just doesn't work as intended. Attachment is comes out as some binary text. Take a look below:
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="==Multipart_Boundary_xf6a3dd3e1c0c1f9233b8c66ce2a73e3ex"Reply-To: <test03#gmail.com>
This is a multi-part message in MIME format.
--==Multipart_Boundary_xf6a3dd3e1c0c1f9233b8c66ce2a73e3ex
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
You've received this e-mail through your website's write an article form:
Name: Johnson
E-mail: test#gmail.com
Regards,
Aakriti
--==Multipart_Boundary_xf6a3dd3e1c0c1f9233b8c66ce2a73e3ex
Content-Type: image/jpeg;
name="599307_322143481199958_2058932593_n.jpg"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="599307_322143481199958_2058932593_n.jpg"
/9j/4AAQSkZJRgABAgAAAQABAAD//gAEKgD/4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNtcwIQAABt
bnRyUkdCIFhZWiAH3AABABkAAwApADlhY3NwQVBQTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
9tYAAQAAAADTLWxjbXMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAApkZXNjAAAA/AAAAF5jcHJ0AAABXAAAAAt3dHB0AAABaAAAABRia3B0AAABfAAAABRyWFla
AAABkAAAABRnWFlaAAABpAAAABRiWFlaAAABuAAAABRyVFJDAAABzAAAAEBnVFJDAAABzAAAAEBi
VFJDAAABzAAAAEBkZXNjAAAAAAAAAANjMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB0ZXh0AAAA
AEZCAABYWVogAAAAAAAA9tYAAQAAAADTLVhZWiAAAAAAAAADFgAAAzMAAAKkWFlaIAAAAAAAAG+i
AAA49QAAA5BYWVogAAAAAAAAYpkAALeFAAAY2lhZWiAAAAAAAAAkoAAAD4QAALbPY3VydgAAAAAA
AAAaAAAAywHJA2MFkghrC/YQPxVRGzQh8SmQMhg7kkYFUXdd7WtwegWJsZp8rGm/fdPD6TD////b
AEMABgQEBQQEBgUFBQYGBgcJDgkJCAgJEg0NCg4VEhYWFRIUFBcaIRwXGB8ZFBQdJx0fIiMlJSUW
HCksKCQrISQlJP/bAEMBBgYGCQgJEQkJESQYFBgkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk
JCQkJCQkJCQkJCQkJCQkJCQkJCQkJP/CABEIAS8B4AMAIgABEQECEQH/xAAbAAACAwEBAQAAAAAA
AAAAAAAABQIDBAEGB//EABgBAQEBAQEAAAAAAAAAAAAAAAABAgME/8QAGAEBAQEBAQAAAAAAAAAA
AAAAAAECAwT/2gAMAwAAARECEQAAAfqgAAAHAPOabh2Vwm7+QWo06vqZa9w57WxTTLsFDRJ
UPDATE: Finally got it fixed after breaking my head for hours..
there were couple of problems:
As pointed out by asachanfbd mime
boundary was not properly nested.
This was one is silly & yet it was the main culprit - extra line breaks at below line of code:
$message .= "\nRegards,\nAakriti \n";
$headers = "From: {$data['name']} <{$data['email']}> \n";
Thanks everyone!

Not much of an answer to your question, but
you could have a look on PHPMailer and on its example.
It is pretty easy to add attachments with PHPMailer.

In a mail mime boundary is used to enclose different part of the mail. In your implementation you did not enclosed body of the mail in required mime type. Also keep in mind that mime boundary for the mail needs to be same for entire mail.
You can use these set of functions for easy implementation.
http://pastebin.com/AbZjzYdv

Related

send PHP mail with Content-Type: multipart/alternative

I am trying to send a multipart mail that contains both html and plain text. This is also one of the ways to get through spam filters and to allow more people to read the mail in case of not supporting HTML. After spending long hours googling, I have found some examples. I made my code, which sends the mail but it displays the text with the html tags, code, string etc.
<?php
$boundary=md5(uniqid(rand()));
$header .= "From:My Name<something#something.com>\n";
$header .= "Reply-To: something#something.com \n";
$header .= 'MIME-Version: 1.0'."\r\n";
$header .= 'Content-type: multipart/alternative;boundary=$boundary '."\n";
$adres = "something#gmail.com";
$subject = "subject";
$message = "This is multipart message using MIME\n";
$message .= "--" . $boundary . "\n";
$message .= "Content-type: text/plain;charset=iso-8859-1\n";
$message .= "Content-Transfer-Encoding: 7bit". "\n\n";
$message .= "Plain text version\n\n";
$message .="--" . $boundary . "\n";
$message .="Content-type: text/html;charset=iso-8859-1\n";
$message .= "Content-Transfer-Encoding: 7bit". "\n\n";
$message .="<html>
<body>
<center>
<b>HTML text version</b>
</center>
</body>
</html>\n\n";
$message .= "--" . $boundary . "--";
if(mail($adres, $subject, $message, $header))
{
print'message sent';
}
else
{
print'message was not sent';
}
?>
This is the result:
This is multipart message using MIME
--c071adfa945491cac7759a760ff8baeb
Content-type: text/plain;charset=iso-8859-1
Content-Transfer-Encoding: 7bit
Plain text version
--c071adfa945491cac7759a760ff8baeb
Content-type: text/html;charset=iso-8859-1
Content-Transfer-Encoding: 7bit
<html>
<body>
<center>
<b>HTML text version</b>
</center>
</body>
</html>
--c071adfa945491cac7759a760ff8baeb--
As you can see it displays the coding instead of the message alone. I have tried many solutions posted like:
adding/removing \r\n;
changing \r\n to \n;
changing content type from alternative to mixed;
I am learning PHP and all I know is all I have read and done so far. I have still much to learn so please if you could tell me where is the problem. I would be very thankful.Best regards.
The line:
$header .= 'Content-type: multipart/alternative;boundary=$boundary '."\n";
Has the wrong quotes, so $boundary won't be expanded. Change to:
$header .= "Content-type: multipart/alternative;boundary=$boundary\n";
And like I said in the comments, in the message headers and the content section headers you should be using \r\n as the line break since that's what is defined in the RFC. Most MTAs will allow simply \n, but some will choke on the message, and some spam filters will count every RFC violation as a point towards your spam score.
Using something like PHPMailer is a much better option because it formats everything perfectly by default, and abides by just about every single obscure, boring RFC.
I think you need quotes around the boundary string.
try this:
$header .= 'Content-type: multipart/alternative; boundary="' . $boundary . '"\r\n';
Try this example https://github.com/breakermind/PhpMimeParser/blob/master/PhpMimeClient_class.php
$m = new PhpMimeClient();
// Add to
$m->addTo("email#star.ccc", "Albercik");
$m->addTo("adela#music.com", "Adela");
// Add Cc
$m->addCc("zonk#email.au");
// Add Bcc
$m->addBcc("boos#domain.com", "BOSS");
// Add files inline
$m->addFile('photo.jpg',"zenek123");
// Add file
$m->addFile('sun.png');
// create mime
$m->createMime("Witaj!",'<h1>Witaj jak się masz? <img src="cid:zenek123"> </h1>',"Wesołych świąt życzę!","Heniek Wielki", "hohoho#domain.com");
// get mime
// $m->getMime();
// Show mime
echo nl2br(htmlentities($m->getMime()));
Here is the complete script without errors:
<?php
error_reporting(-1);
ini_set("display_errors", "1");
$mailto = "email#enter-domainname-here.com";
$subject = "subject";
$boundary=md5(uniqid(rand()));
$header = "From:Info<".$mailto.">\n";
$header .= "Reply-To: ".$mailto."\n";
$header .= "MIME-Version: 1.0"."\n";
$header .= "Content-type: multipart/alternative; boundary=\"----=_NextPart_" . $boundary . "\"";
$message = "This is multipart message using MIME\n";
$message .= "------=_NextPart_" . $boundary . "\n";
$message .= "Content-Type: text/plain; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 7bit". "\n\n";
$message .= "Plain text version\n\n";
$message .="------=_NextPart_" . $boundary . "\n";
$message .="Content-Type: text/html; charset=UTF-8\n";
$message .= "Content-Transfer-Encoding: 7bit". "\n\n";
$message .="<html>
<body>
<center>
<b>HTML text version</b>
</center>
</body>
</html>\n\n";
$message .= "------=_NextPart_" . $boundary . "--";
if(#mail($mailto, $subject, $message, $header))
{
print'message sent';
}
else
{
print"message was not sent";
}
?>

sending file attachment via html form sends big junk of text to the email body

I am trying to make a html file upload to send via email with php. Here is the code snippet:
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
$filename = $_FILES['file']['name'];
$boundary =md5(date('r', time()));
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$body="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
test
--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
mail('email#example.com', 'Leidige stillinger', $body, $headers) or die("NO");
I get the email but with a junk of text, looks like the $boundary generates that big junk of text. Or I am doing this all wrong, first I have to upload the file somewhere in the server then send it via email
I've always preferred hand-rolling the MIME encoding as well, like you're doing, instead of using a library. You're close. Try this:
// to, from, subject, message body, attachment filename, etc.
$to = "to#to.com";
$from = "from#from.com";
$subject = "subject";
$message = "this is the message body";
$filename="/home/user/file.pdf"; //location of file - path and filename
$fname="file.jpeg"; //name of file for display purposes
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
$file = fopen($filename,"rb");
$data = fread($file,filesize($fname));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$fname\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$fname\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
$ok = #mail($to, $subject, $message, $headers, "-f " . $from);

Sending an email with attachment displays in encoded format PHP

This is the code am using to send an email with a doc file attached to it,
am receiving the email but the content in the email is displaying in a encoded text format
<?php
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$fileatt = $_FILES['upload_file']['tmp_name'];
$fileatt_type = $_FILES['upload_file']['type'];//application/msword
$fileatt_name = $_FILES['upload_file']['name'];
$headers = "From: $from";
if (is_uploaded_file($fileatt)) {
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
}
mail($to, $subject, $message, $headers);
?>
email am receiving is like this
message:This is a multi-part message in MIME format. --==Multipart_Boundary_x788f8ac40875c8c7a6540be6654be9c8x Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit --==Multipart_Boundary_x788f8ac40875c8c7a6540be6654be9c8x Content-Type: application/msword; name="File_name.doc" Content-Disposition: attachment; filename="File_name.doc" Content-Transfer-Encoding: base64 s pcEAW4AJBAAA+BK/AAAAAAAAEAAAAAAACAAAMhMAAA4AYmpiaqz6rPoAAAAAAAAAAAAAAAAAAAAA AAAJBBYAuEAAAM6QAQDOkAEAFwsAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAA AAAAAAD//w8AAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAALcAAAAAAEgHAAAAAAAASAcAAIsU AAAAAAAAixQAAAAAAACLFAAAAAAAAIsUAAAAAAAAixQAADQAAAAAAAAAAAAAAP////8AAAAAvxQA AAAAAAC/FAAAAAAAAL8UAABoAAAAJxUAAEwAAABzFQAAbAAAAL8UAAAAAAAAj0UAAMYCAADfFQAA FgAAAPUVAAAQAAAABRYAAAAAAAAFFgAAAAAAAAUWAAAAAAAAJBcAACYAAABKFwAADAAAAFYXAAAI AAAADkUAAAIAAAAQRQAAAAAAABBFAAAAAAAAEEUAAAAAAAAQRQAAAAAAABBFAAAAAAAAEEUAACQA AABVSAAAogIAAPdKAAA8AAAANEUAABUAAAAAAAAAAAAAAAAAAAAAAAAAixQAAAAAAABeFwAAAAAA AAAAAAAAAAAAAAAAAAAAAAAkFwAAAAAAACQXAAAAAAAAXhcAAAAAAABeFwAAAAAAADRFAAAAAAAA AAAAAAAAAACLFAAAAAAAAIsUAAAAAAAABRYAAAAAAAAAAAAAAAAAAAUWAAAfAQAASUUAABYAAADc GgAAAAAAANwaAAAAAAAA3BoAAAAAAABeFwAADAEAAIsUAAAAAAAABRYAAAAAAACLFAAAAAAAAAUW AAAAAAAADkUAAAAAAAAAAAAAAAAAANwaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAXhcAAAAAAAAORQAAAAAAAAAAAAAAAAAA3BoAAAAAAADcGgAA pgEAAJY+AAAwAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKkIAAAAAAAAFFgAAAAAAAP////8AAAAA0NGIQpry zAEAAAAAAAAAAL8UAAAAAAAAahgAACIAAADGPwAAJAAAAAAAAAAAAAAA+kQAABQAAABfRQAAMAAA AI9FAAAAAAAA6j8AAEACAAAzSwAAAAAAAIwYAABQAgAAM0sAAEgAAAAqQgAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAADNLAAAAAAAAAAAAAAAAAACLFAAAAAAAACpCAADQAgAAXhcAAAAAAABeFwAAAAAAANwa AAAAAAAAXhcAAAAAAABeFwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAXhcA AAAAAABeFwAAAAAAAF4XAAAAAAAANEUAAAAAAAA0RQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAA== --==Multipart_Boundary_x788f8ac40875c8c7a6540be6654be9c8x--
headers:From: MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="==Multipart_Boundary_x788f8ac40875c8c7a6540be6654be9c8x"
So can anyone help me with a perfect code
Thank u in advance
Find out the reason yourself by really debugging the issue at hand instead of guessing:
Dump the messages content you generate into a text file.
Dump any valid messages content you received in an email client into a file (the messages SOURCE code).
Compare both files and take your answer from the difference.
That works, really.
PHP doesn't support default utf-8 encoding, you need to pass the relevant encoding function as given in the following to your headers
Replace your code
Content-Type: text/plain; charset=\"iso-8859-1\"\n
to
"Content-Type:text/html;charset=utf-8"

CSV attachment in PHP

I am trying to send a CSV file as an attachment in PHP and using mail function for attachments. The following code works fine. It successfully attaches the CSV file and sends it to the recipient but the ATTACHED output file (sent in email) comes in text format(.txt). I don't know where i am making mistake and what i need to change in header to retain original CSV file format in attached email.
$path ="/myhost/public_html/csv/";
$file_name = $path."Test";
$file_name.=".csv";
$from = "some#myemail.co.uk";
$to = "other#hisemail.co.uk";
$fat=$file_name;
$subject = $_POST[subject];
// $message = $_POST[message];
//replace \n with <br>
$message = str_replace("\n", "<br>",$message);
//report
echo "<b><font color=#8080FF> From: $from </b><br>";
echo "<b>To: $to </b><br>";
echo "<b>Subject: $subject</b><br><br></font>";
// Obtain file upload variables
$fileatt = $_FILES[$fat]['tmp_name'];
$fileatt_type = $_FILES[$fat]['type'];
$fileatt_name = $_FILES[$fat]['name'];
$headers = "From: $from \n";
// if($_FILES['fileatt']['size'] > 0)
if (file_exists($fat)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fat,'rb');
$data = fread($file,filesize($fat));
fclose($file);
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "MIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Base64 encode the file data
$data = chunk_split(base64_encode($data));
// Add file attachment to the message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
} else echo "File error! ";
//send the mail
if(mail($to, $subject, $message,$headers))echo "<b><font color=#FF0000>Message was sent!<b></font>";
else echo "<b><font color=#FF0000>Message error!<b></font>";
I just want to retain original file format in email attachments. Help me please.
I would recommend using a library to handle email attachments. This kind of thing can get complicated quickly and someone else out there has already figured out all the ins and outs of what needs to happen when CSV files are attached. I would use something like http://swiftmailer.org/
You could do all of the code you have above, or something more like...
require_once 'lib/swift_required.php';
$message = Swift_Message::newInstance()
->setSubject('Your subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
->addPart('<q>Here is the message itself</q>', 'text/html')
->attach(Swift_Attachment::fromPath('my-document.csv'));
Example from: http://swiftmailer.org/docs/messages.html
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
this might be helpful ?

PHP mail() attachment is corrupt

I have been struggling with trying to send an email with an attachment using PHP. It used to work but the message body was scrambled. Now I have got the message body to work but the attachment corrupts. I used to use base64 encoding for the message body but now use 7bit. Can anyone tell me what I am doing wrong?
PS please do not tell me that I should be using a pre-made class to do this. I have tried several and they have all failed to work. If I do not overcome these problems I will never learn how to do it properly. Thanks
//define the receiver of the email
$to = 'a#something.co.uk';
//define the subject of the email
$subject = 'Your Disneyland Paris entry';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \n
$mime_boundary = "<<<--==+X[".md5(time())."]";
$path = $_SERVER['DOCUMENT_ROOT'].'/two/php/';
$fileContent = chunk_split(base64_encode(file_get_contents($path.'CTF_brochure.pdf')));
$headers .= "From: info#blah.org.uk <info#blah.org.uk>"."\n";
$headers .= "MIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n";
$message .= "\n";
$message .= "--".$mime_boundary."\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 7bit\n";
$message .= "\n";
$message .= "messagebody \n";
$message .= "--".$mime_boundary."" . "\n";
$message .= "Content-Type: application/octet-stream;\n";
$message .= " name=\"CTF-brochure.pdf\"" . "\n";
$message .= "Content-Transfer-Encoding: 7bit \n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"CTF_brochure.pdf\"\n";
$message .= "\n";
$message .= $fileContent;
$message .= "\n";
$message .= "--".$mime_boundary."--\n";
//send the email
$mail_sent = mail($to, $subject, $message, $headers);
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
I could be wrong but I believe you will have to encode the PDF somehow, 7bit won't work as the PDF file will have content outside the range. Why not use base64 for the PDF?
I would suggest looking at phpmailer if you want to do complex email.
I know you've said about pre-built classes but there is a reason that people do this - why re-invent the wheel? I use SwiftMailer for projects - it couldn't be simpler. See this SwiftMailer example for 13 lines (including some blank ones) of how to create a message, add an attachment and send.
As to the resolution of your actual query, upvote to Josh's answer - I'd second changing the encoding and seeing how you get on. Have you tried getting an example email message which has an attachment that works, and examining the raw data?

Categories