Send attachment file using mail () in PHP - php

I had reference this solution from other post and I tried modify the content to suit my requirement.
Here is the code that I implemented to send attachment file via mail using PHP.
$htmlbody = " Your Mail Contant Here.... You can use html tags here...";
$to = "foo#bar.com"; //Recipient Email Address
$subject = "Test email with attachment"; //Email Subject
$headers = "From: foo#bar.com\r\nReply-To: foo#bar.com";
$random_hash = md5(date('r', time()));
$headers .= "\r\nContent-Type: multipart/mixed;
boundary=\"PHP-mixed-".$random_hash."\"";
// Set your file path here
$path = $_FILES["cv"]["name"];
$attachment = chunk_split(base64_encode(file_get_contents($path)));
//define the body of the message.
$message = "--PHP-mixed-$random_hash\r\n"."Content-Type: multipart/alternative;
boundary=\"PHP-alt-$random_hash\"\r\n\r\n";
$message .= "--PHP-alt-$random_hash\r\n"."Content-Type: text/plain;
charset=\"iso-8859-1\"\r\n"."Content-Transfer-Encoding: 7bit\r\n\r\n";
//Insert the html message.
$message .= $htmlbody;
$message .="\r\n\r\n--PHP-alt-$random_hash--\r\n\r\n";
//include attachment
$message .= "--PHP-mixed-$random_hash\r\n"."Content-Type: application/zip;
name=\"$path\"\r\n"."Content-Transfer-Encoding:
base64\r\n"."Content-Disposition: attachment\r\n\r\n";
$message .= $attachment;
$message .= "/r/n--PHP-mixed-$random_hash--";
//send the email
$mail = mail( $to, $subject , $message, $headers );
echo $mail ? "Mail sent" : "Mail failed";
I able to get the attachment file but I cant open it.
It show me the error of "The application you chose ("") could not be found. Check the file name or choose another application."
Can anyone correct my error..?

It seems that the problem relies in the file name after download. The server did the job and sent the email and this is rather a client side problem.
Check the filename extension and make sure it is the same as the side that sent it, If not make sure u correct your PHP code naming function.
Make sure the application that reads that filetype is available on your PC.
Try to open the file on a different computer.

Related

PHP mail with attachment, attachment file is noname

I have the following code, which correctly sends an email with an attachment of the correct size, however the attachment comes in as 'noname' without an extension. If I rename the file manually after downloading it does not work. The file is an mp4 video.
<?php
$htmlbody = " Your Mail Contant Here.... You can use html tags here...";
$to = "blah#gmail.com"; //Recipient Email Address
$subject = "Test email with attachment"; //Email Subject
$headers = "From: test#mysite.com\r\nReply-To: test#mysite.com";
$random_hash = md5(date('r', time()));
$headers .= "\r\nContent-Type: multipart/mixed;
boundary=\"PHP-mixed-".$random_hash."\"";
// Set your file path here
$attachment = chunk_split(base64_encode(file_get_contents('test.mp4')));
//define the body of the message.
$message = "--PHP-mixed-$random_hash\r\n"."Content-Type: multipart/alternative;
boundary=\"PHP-alt-$random_hash\"\r\n\r\n";
$message .= "--PHP-alt-$random_hash\r\n"."Content-Type: text/plain;
charset=\"iso-8859-1\"\r\n"."Content-Transfer-Encoding: 7bit\r\n\r\n";
//Insert the html message.
$message .= $htmlbody;
$message .="\r\n\r\n--PHP-alt-$random_hash--\r\n\r\n";
//include attachment
$message .= "--PHP-mixed-$random_hash\r\n"."Content-Type: video/vnd.uvvu.mp4
name=\"testing.mp4\"\r\n"."Content-Transfer-Encoding:
base64\r\n"."Content-Disposition: attachment\r\n\r\n";
$message .= $attachment;
$message .= "/r/n--PHP-mixed-$random_hash--";
//send the email
$mail = mail( $to, $subject , $message, $headers );
echo $mail ? "Mail sent" : "Mail failed";
?>
Just modify this line, everything else stays the same:
$filename= "myvideo.mp4";
//include attachment
$message .= "--PHP-mixed-$random_hash\r\n"."Content-Type: video/vnd.uvvu.mp4
name=\"testing.mp4\"\r\n"."Content-Transfer-Encoding:
base64\r\n"."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";

How to use TCPDF with PHP mail function

$to = 'my#email.ca';
$subject = 'Receipt';
$repEmail = 'rep#sales.ca';
$fileName = 'receipt.pdf';
$fileatt = $pdf->Output($fileName, 'E');
$attachment = chunk_split($fileatt);
$eol = PHP_EOL;
$separator = md5(time());
$headers = 'From: Sender <'.$repEmail.'>'.$eol;
$headers .= 'MIME-Version: 1.0' .$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
$message = "--".$separator.$eol;
$message .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$message .= "This is a MIME encoded message.".$eol;
$message .= "--".$separator.$eol;
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$message .= "--".$separator.$eol;
$message .= "Content-Type: application/pdf; name=\"".$fileName."\"".$eol;
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment".$eol.$eol;
$message .= $attachment.$eol;
$message .= "--".$separator."--";
if (mail($to, $subject, $message, $headers)){
$action = 'action=Receipt%20Sent';
header('Location: ../index.php?'.$action);
}
else {
$action = 'action=Send%20Failed';
header('Location: ../index.php?'.$action);
}
I have been using TCPDF for a short amount of time now to generate PDF files from forms. It works quite well and that part of the PHP has not changed. Now I want to send those PDF files to my email account.
The emailing is actually working with this coding and attaching a PDF. The issue is that it is simply a blank PDF at rough 100 bytes in size. Which of course is not a valid PDF nor does it have anything to do with the responses from the form.
I am really not familiar with the attaching of files to an email in PHP and any help resolving this issue would be greatly appreciated.
Update
Since it seems like several people are looking at this still I will post my current solution. It involves downloading PHPMailer as suggested below. I have started at the output line for TCPDF.
$attachment = $makepdf->Output('filename.pdf', 'S');
SENDmail($attachment);
function SENDmail($pdf) {
require_once('phpmailer/class.phpmailer.php');
$mailer = new PHPMailer();
$mailer->AddReplyTo('reply#to.ca', 'Reply To');
$mailer->SetFrom('sent#from.ca', 'Sent From');
$mailer->AddReplyTo('reply#to.ca', 'Reply To');
$mailer->AddAddress('send#to.ca', 'Send To');
$mailer->Subject = 'Message with PDF';
$mailer->AltBody = "To view the message, please use an HTML compatible email viewer";
$mailer->MsgHTML('<p>Message contents</p>'));
if ($pdf) {$mailer->AddStringAttachment($pdf, 'filename.pdf');}
$mailer->Send();
}
You have two choices. You can save the PDF to a file and attach the file or else output it as a string. I find the string output is preferable:
$pdfString = $pdf->Output('dummy.pdf', 'S');
The file name is ignored since it just returns the encoded string. Now you can include the string in your email. I prefer to use PHPMailer when working with attachments like this. Use the AddStringAttachment method of PHPMailer to accomplish this:
$mailer->AddStringAttachment($pdfString, 'some_filename.pdf');
I tried several alternatives. Only way that worked was when I saved the PDF to a folder and then email it.
$pdf->Output("folder/filename.pdf", "F"); //save the pdf to a folder
require_once('phpmailer/class.phpmailer.php'); //where your phpmailer folder is
$mail = new PHPMailer();
$mail->From = "email.com";
$mail->FromName = "Your name";
$mail->AddAddress("email#yahoo.com");
$mail->AddReplyTo("email#gmail.com", "Your name");
$mail->AddAttachment("folder/filename.pdf"); // attach pdf that was saved in a folder
$mail->Subject = "Email Subject";
$mail->Body = "Email Body";
if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
echo "Message sent";
}
echo 'sent email and attachment';

Sending an image to email via PHP

can you please help me with this code. i am trying to embed a image in my mail and its showing as string of alphanumeric ..
function send_mail_pear()
{
$crlf = "\n";
$to = "mail#mail.in";
$head = ("From: mail#mail.in". "\r\n");
$head .= "Content-type: text/html\r\n";
$head .= "Content-Type: image/jpeg";
$mime = new Mail_mime($crlf);
echo $head. "<br/>";
$mime->setHTMLBody('<html><body><img src="map_6.gif"> <p>You see this image.</p></body></html>');
$mime->addHTMLImage('map_6.gif', 'image/gif');
$subject = "Test mail";
$mailBody = $mime->get();
$mail =& Mail::factory('mail');
echo $mailBody ;
/*if(mail($to, $subject, $mailBody, $head)){
echo "successful";
} else {
echo "Mail Not sent";
}
}
I believe you have to link to the image as "cid:yourcontentid", and specify "yourcontentid" as a parameter to addHTMLImage.
You can consult the documentation for more information.
you can just attach it using. or i suggest the least painful option will be to host the image on some server and send an HTML email.
the body will look like
<html>
<p>
<img src='http://yourserver.com/YOURIMAGE.gif' />
</p>
</html>
EDIT:
to attach images or files to an email try something like this
$to = "someome#anadress.com";
$from = "SOME NAME ";
$subject = "SUBJECT";
$fileatt = "./FILENAME.gif";
$fileatttype = "image/gif";
$fileattname = "ATTACHMENTNAME.gif";
$headers = "From: $from";
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
$data = chunk_split(base64_encode($data));
$rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$rand}x";
$headers .= <<<HEADER
MIME-Version: 1.0\n
Content-Type: multipart/mixed;\n
boundary="{$mime_boundary}"
HEADER;
$message = <<<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
\n\n
–{$mime_boundary}\n
Content-Type: {$fileatttype};\n
name="{$fileattname}"\n
Content-Disposition: attachment;\n
filename="{$fileattname}"\n
Content-Transfer-Encoding: base64\n\n
{$data}\n\n
-{$mime_boundary}-\n
MESSAGE;
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
The answer by Matthias Vance is part of the story.
If you want to send a self-contained HTML mail, then it needs to be sent as an mhtml type (NB the content type for this varies on different implementations - it should be multipart/related but frequently is message/rfc822). There is however a formal definition of the structure in RFC 2557. Each of the components should be a seperate attachment. This also means that each URL has to be rewritten to use a local reference and the cid scheme - IIRC, the PEAR class does not do this for you.
There is some documentation on the net e.g. this one - but do not fall into the trap of believing this is suitable for anything other than sending emails / saving web pages locally - MSIE does not handle mhtml files delivered over HTTP correctly.
I'm not aware of any off the shelf package for generating mhtml files / emails - but there are some for parsing such files. Writing a tool to do this would be straightforward but not trivial.

why is my form submitting to an excel file?

Okay all, I have a form that I want users to fill out. When They click submit, I want the contents of this form to be put into a message, and I want the contents to be added to an excel file. Then I want the message that is sent to the recipient to have an attachment of that excel file. You will see partial mime code, I have no Idea how to use it, that was my attempt at figuring this out... Heres what I have so far:
I guess the main question is more specifically, what in the code is making the contents the user submits, automatically go into an excel file and attach itself to the email?
$date = $_POST['date'];
$org =$_POST['Org'];
$activity =$_POST['activ'];
$dofevent = $_POST['dateoe'];
$money= $_POST['amountreq'];
$name =$_POST['name'];
$email =$_POST['email'];
$phone =$_POST['pnumber'];
$dateneeded =$_POST['datenb'];
//bottom
$semester =$_POST['semester'];
$question7a =$_POST['7a'];
$question7b =$_POST['7b'];
$mime_boundary = "<<<--==+X[".md5(time())."]";
$headers .= "From: SAF Request Form ";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed;\r\n";
//$headers .= " boundary=\"".$mime_boundary."\"";
$subject .="SAF Request Form";
//$message .= "This is a multi-part message in MIME format.\r\n";
//$message .= "\r\n";
//$message .= "--".$mime_boundary."\r\n";
//$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
//$message .= "Content-Transfer-Encoding: 7bit\r\n";
$message ="this is where I put my message";
mail ("20valvesofturbo#gmail.com",$subject,$message, $headers);
if( mail( "20valvesofturbo#gmail.com", $subject, $message, $headers ) ) {
echo "<p>The email was sent.</p>";
}
else {
echo "<p>There was an error sending the mail.</p>";
}
// start of xcel spreadsheet and header-->
$reg = "../data/eforms/saf/reg.xls";
$ft = fopen($reg,'a');
fwrite($ft,"header information");
// start of information submitted by user
fwrite($ft, $org);
fwrite($ft,"user submitted data");
fclose($ft);
//adds all the data
// individual excell sheet
$reg = "../data/eforms/saf/names/$org.xls";
$ft = fopen($reg,'w+');
fwrite($ft,"blablabla");
fclose($ft);
?>
what this does is it submits the data and sends a message, but it sends the data in an unknown file format as an attachment. If you open it in excel, it has the contents of the message...
Thanks!
For generating MIME encoded messages, I suggest that you use the Pear::Mail_Mime package ( http://pear.php.net/package/Mail_Mime). As for generating an Excel file, you can have a look at http://pear.php.net/package/Spreadsheet_Excel_Writer; depending on the complexity of the data to put into Excel, you could possibly also use just a CSV file

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