PHP mass mail script shows extra file in outlook - php

I use PHP script to send email with multiple attachments, it works great for gmail, but in Microsoft Outlook i also see blank file ATT00010.txt (random numbers.) as attachment. And when i send email from outlook with multiple attachments as well it does not show no file like this.
I echo'ed output from email script and there is no such file in code. Can someone tell me how to remove this file from outlook?
Email script is below.
// array with filenames to be sent as attachment
$files = array("file_1.ext","file_2.ext","file_3.ext",......);
// email fields: to, from, subject, and so on
$to = "mail#mail.com";
$from = "mail#mail.com";
$subject ="My subject";
$message = "My message";
$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
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}

If you want something that's a little less of a pain to use and send attachments with, try Swift Mailer. (swiftmailer.org) I've been using it in my projects and it works great.
Here's an example:
$message = Swift_Message::newInstance()
->setSubject('Webinar Registration')
->setFrom(array('replyto#example.org' => 'From Name'))
->setTo(array('destination#example.org'))
->setBody($MESSAGE_TEXT)
;
$message->attach(Swift_Attachment::fromPath('SOME_FILE_PATH'));
$transport = Swift_SmtpTransport::newInstance('127.0.0.1', 25);
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($message);
Just my two cents.
Otherwise, I was going to mention what someone else already beat me to -- check the boundaries.

The last boundary line in a multipart/* message must have -- appended at the end, in addition to what all of the other boundary lines have. A consumer can use that to recognize the end of a message.
Apparently Outlook treats the absence of the correct ending as an indication that the message has been truncated, and then does the best it can to display whatever it did receive.

Its my second account, i actually found solution and don't need no library or class at all although i might turn this into class and add some stuff, its always better to have full understanding of process not just from, to, files etc fields.
Solution is simple here just replace last part with
if ($x == count($files)-1)
$message .= "--{$mime_boundary}--\r\n";
else
$message .= "--{$mime_boundary}\n";
\r is not necessary
if you just put -- it will use it many times inside loop IF checks if this is last loop.

Related

Php mail not working with more than one recipient

How come this piece of php code doesn't work with multiple recipient ?
It only works if $to has only one adress, like:
$to = 'aa#bb.com';
Edit
It works if email adresses are on the same domain.. For instance, if the website is www.example.com, emails such as xxx#example.com will work but yyy#other.com won't.
Solution
PHPMailer. It gives an easy way to configure SMTP.
Here is the initial code
<?php
//define the receiver of the email
$to = 'aa#bb.com, cc#dd.com, ee#ff.com';
// array with filenames to be sent as attachment
$files = array("a.zip","b.c","a.html");
// email fields: to, from, subject, and so on
$from = "mail#mail.com";
$subject ="My subject";
$message = "My message";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers = "From: $from";
$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
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
?>
Here is the final code
// PHPMailer
$mail = new PHPMailer;
// setting up PHPMailer
$mail->isSMTP();
$mail->Host = 'host.com';
$mail->SMTPAuth = false;
$mail->Port = xx;
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->Subject = $_POST['subject'];
$mail->msgHTML($_POST['message']);
foreach($contacts as $contact)
$mail->addAddress($contact['email']);
// If the user has attached some files
foreach ($_FILES as $file)
$mail->addAttachment($file['tmp_name'], basename($file['name']));
$response = array("status" => $mail->send() ? "sent" : "error");
echo json_encode($response);
You need use proper RFC 2822 formating.
Don't use # because you don't know what is the error. If you format mails in format "user#example.com, anotheruser#example.com" it's correct and you need search problem elsewhere.
You can also see example #4 on http://php.net/manual/en/function.mail.php#example-3493 page.
although this is not a direct response to your issue, you could potentially save yourself trouble by using a pre-existing email sending library like either:
phpmailer
https://github.com/PHPMailer/PHPMailer
or simplesmtp
https://bitbucket.org/ghorwood/simplesmtp/

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 - trying to send email from script with attachment, but its not attachingHi

I have a file that I am creating on the fly like this:
// Create and save the string on the file system
$str = "Business Plan: \nSome more text";
$fp = fopen("alex.txt", 'w+');
fwrite($fp, $str);
// email with the attachment
$to = 'alex.genadinik#gmail.com';
$subject = 'Your business plan attached';
//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 \r\n
$headers = "From: BusinessPlanApp#example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('alex.txt')));
$contents = "some contents of the email";
mail($to, $subject, $contents, $headers);
And the file is saving to the file system AND an email is getting sent to me with the right body and subject.
The only thing going wrong is the attachment is unnamed file of zero bytes. Any idea why that might happen? Is it a permissions issue? Or something in my email?
Thanks!
You're putting your mime data into $attachment, but then don't use that variable anywhere, so you're not actually attaching anything.
You'd be better off using a library, such as PHPMailer or Swiftmailer, to do this for you. It's far less hassle and they provide FAR better diagnostics in case of trouble.
You email code seems to be missing a few things. I began fixing it but it might be better to start from scratch. I'd recommend a library, but if not, the following code should achieve what you want:
// Create and save the string on the file system
$str = "Business Plan: \nSome more text";
$fp = fopen("alex.txt", 'w+');
fwrite($fp, $str);
fclose($fp);
// email fields: to, from, subject, and so on
$from = "BusinessPlanApp#example.com";
$to = 'alex.genadinik#gmail.com';
$subject = 'Your business plan attached';
$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}\"";
// message text
$contents = "This is the email content";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $contents. "\n\n";
// preparing attachments
$message .= "--{$mime_boundary}\n";
$fp = fopen('alex.txt',"rb");
$data = fread($fp,filesize('alex.txt'));
fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename('alex.txt')."\"\n" .
"Content-Description: ".basename('alex.txt')."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename('alex.txt')."\"; size=".filesize('alex.txt').";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
mail($to, $subject, $message, $headers);

Emailing Photos to my Facebook Page

We run the facebook fan page www.facebook.com/GowerLive which features images and updates from our 3 web cameras on the Gower Peninsula; I want to use the feature on Facebook which allows you to email photos directly to your fan page using a unique email address on a CRON job at 8pm each day.
I have tested the email address... That works fine and I can submit images however my PHP Script doesn't display the photos. It will post the subject to facebook but that's it.
Firstly, is this the best way to get the images up to my fan page?
Secondly, am I using the right format of email for this to work as in Multipart Mime Type?
This is my script which I currently have running on a cron
// array with filenames to be sent as attachment
$files = array("public_html/langcam/09.jpg","public_html/langcam/13.jpg","public_html/langcam/16.jpg","public_html/caswellcam/09.jpg","public_html/caswellcam/13.jpg","public_html/caswellcam/16.jpg","public_html/llangcam/09.jpg","public_html/llangcam/13.jpg","public_html/llangcam/16.jpg");
// email fields: to, from, subject, and so on
$to = "uniqueaddress#m.facebook.com";
$from = "email#mysite.com";
$subject = "On ".date("F j, Y")." the wavebuoy at 1pm was ". $waveheightb."ft # ".$seconds."seconds with a ".$windcompass." wind at ".$windspeedb."mph";
$message = "I normally leave this blank";
$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
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "Mail sent to $to!";
} else {
echo "Mail could not be sent!";
}
thanks
Lee
Lee,
You might want to look at the Facebook Graph API. I'm not sure if it will work on Fan pages, but see no reason for it not to. Ignore the blog post title and scroll down to the second piece of the article as to how to create an album and upload photos to it.
https://developers.facebook.com/blog/post/498/
The Facebook Graph API page to do with photos is located at the following URL:
http://developers.facebook.com/docs/reference/api/photo/
Or alternatively create an ifttt script on http://ifttt.com as it might be easier.
Jon

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