Sending attachment from file input in form - php

Hello I have a simple form which collect files. What I mean is that user should be able to put a file into the field and then by submitting the form mail should be sent to the address which is predefined and hardcoded.
here is my form:
<form action='/?page=admin-send' method='post' class='asholder' enctype=\"multipart/form-data\">\n";
<input type='file' name='file' id ='file'/><button name='accept' value='".$ssl->id."' type='submit'>Send</button>
</form>
And now using Php I want to collect this file and put it into email attachment.
$file = $_FILES["file"]["name"];
$filename = basename($file);
$file_size = filesize($file);
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
$msg = "Hello, this is email with attachment!";
$mail = new HTMLMail();
$mail->from = 'DO NOT REPLY';
$mail->to = 'tstmail#testhost.com';
$mail->subject = 'admin warrning';
$mail->importance = 'Low';
$mail->body = "<P><FONT SIZE=2 FACE=\"Tahoma\">$msg</FONT></P>";
$mail->headers = "From: ".$from."\r\n"
."MIME-Version: 1.0\r\n"
."Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"
."This is a multi-part message in MIME format.\r\n"
."--".$uid."\r\n"
."Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"
."Content-Transfer-Encoding: base64\r\n"
."Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n"
.$content."\r\n\r\n"
."--".$uid."--";
$mail->send();
And here is the scenario I have problem with:
I put file with name of xyz.pdf which is some document the most important thing is that this document is all right. When I submit my form I am getting the email. Email has attachment which name is xyz.pdf but when I am trying to open this file I am getting the message that the file is borken.
Can anyone point me what I am doing wrong?

I have done the same kind of task, i expect that my answer will help you for sure.
You are letting user 1. upload a file > *2.* process it at your server side using PHP > *3.* and them you are using HTML mail class to send your mail.
The problem is in third step. If the class does not provide you with sufficient function of mail, then it is not worth using. Writing mail HEADERS by yourself poses a lot of complexity and we as a developer should not go that inside.
I recommend you to use PHPMailer 5.1.2, to do this job. This is very simple and is of not more than 80KB (the core files, excluding demos, guides).
With this you can attach multiple files of any mime type(pdf, jpeg, doc etc.) without worrying about headers. This is very simple and i have tested , the attachments are readable at the mailbox.
If you download complete package with demos, you will see how easy it is to implement with PHP.
PHPMailer is the best free php class to send mails on the net(i think) with no bugs.
I haven't used HTML Mail class what you are using, so don't know whether it has functions for attaching files. But writing mail headers is not good. If you are using it by your wish after knowing all this, then i am sorry for posting this answer.

Related

Add Picture In Email Body

i am not too good with PHP and programming but still i am trying to learn it in every possible way. I need help from experts. My code to send email is as below. i am able to send email, but the problem is, picture is not displaying in email body and it's showing a cross sign. any possible idea and suggestion is appreciated.
<?php
function send_email($from, $to, $subject, $message){
$headers = "From: ".$from."\r\n";
$headers .= "Return-Path: ".$from."\r\n";
$headers .= "CC: abc#gmail.com\r\n , xyz#gmail.com\r\n";
$headers .= "BCC: \r\n";
//set content type to HTML
$headers .= "Content-type: text/html\r\n";
if ( mail($to,$subject,$message,$headers) )
{
header("location:contact-us.php?msg=msgsent");
}
else
{
header("location:contact-us.php?msg=notsent");
}
}
//Function ends here
$from_email="";
$to_email="LMN#gmail.com";
$message.="<html><body background='images/bg11.jpg'>";
$message.="<p style=' color: #006789;'>Dear Team,</p> ";
$message.= "<p style=' color: #006789;'>You have received a feedback from $name & below are the details!!! </p>";
$message.= "<img src=images/c22.jpg>";
$message.="</body></html> ";
send_email(from_email,$to_email,$subject,$message);
?>
You are using a relative path:
<img src=images/c22.jpg>
When you open your mail, that path will mean nothing in a mail client and it is highly unlikely to exist on a webmail client. And if it does, it is not your image...
If you have that image stored on a web-server, you should use the absolute path to that image:
<img src="http://www.your-server.com/images/c22.jpg">
You're using a relative link, "images/c22.jpg", but you're sending this html in an email - there's no images/ directory relative to it to link to. If you wish to link to an image on the web, you can include a full url (http://someplace.com/images/bg11.jpg">). By default, those will usually not be displayed either - most email readers will filter them so as to not let you cause it to load remote content (tipping off that the email was opened, attempting funny business with malformated images, etc).
You can also attach an image to the email by setting the type to multipart/mixed and defining a boundary. Then send an image, defining a content-id in its headers, then your html linking to the content id as "cid:id-you-defined". Looks like this once in the email:
Content-Type: multipart/mixed; boundary="NOTUSEDINTEXT"
This text only shows if the reader can't deal with MIME
--NOTUSEDINTEXT
Content-Id: id_for_later
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU
FhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo
KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wAARCAABAAEDASIA
AhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFAEB
AAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AJUAB//Z
--NOTUSEDINTEXT
Content-Type: text/html
<html><h1>Hi</h1><p>Here's an image <img src="cid:id_for_later"></html>
--NOTUSEDINTEXT--
.. but as you see it's slightly involved - might want to see if there's a php library that'll implement that (the mime headers and types) rather than pound them in yourself. But if you feel like dealing with it, inserting them yourself is ok too. And.. here too, some clients will filter them for safety unless you've clicked "Always show images" or something.
You have to upload your image on web server and give the absolute path to that image e.g:
<img src="http://www.yourwbesite.com/images/c22.jpg" alt="logo" />

PHP Email Attachment pdf and docx files don't get sent properly

Ok, so while still aware of better solutions, I'm using manual PHP script to send e-mail with an attachment. The only problem I have is that some attachments (PDF, DOCX) are blank when received in an e-mail.
I noticed that when I check $data variable (where the text of the document is stored), in files with extension pdf or docx there are extra characters that are not part of the message in the file. In DOCX file there are some extra characters and in PDF the contents are not displayed at all but some random crap is displayed (encoding?). There should theoretically be a way to attach PDFs and Docx files though.
Not sure how to solve this problem. Would definitely appreciate some help! I'd hate to have to resort to using PHPMailer or SwiftMailer.
Here's my code:
$attachment = $_FILES['uploaded']['tmp_name'];
$att_type = $_FILES['uploaded']['type'];
$att_name = $_FILES['uploaded']['name'];
if (is_uploaded_file($attachment)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($attachment, 'rb');
$data = fread($file, filesize($attachment));
fclose($file);
// Generate boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add headers for file attachment
$from .= "MIME-Version: 1.0\r\n";
$from .= "Content-Type: multipart/mixed; boundary=\"{$mime_boundary}\"\r\n\r\n";
// Message
$message = "This is a multi-part message in MIME format.\r\n";
$message .= "--{$mime_boundary}\r\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n\r\n";
$message .= $msg . "\r\n\r\n";
$data = chunk_split(base64_encode($data));
// Attachment
$message .= "\r\n--{$mime_boundary}\r\n";
$message .= "Content-Type: {$att_type}; name=\"{$att_name}\"\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"{$att_name}\"\r\n\r\n";
$message .= $data . "\r\n";
$message .= "--{$mime_boundary}--\r\n";
} else {
$message = $msg;
}
// Send message
$success = mail($to, $subject, $message, $from);
Is there a way to attach PDF and docx files that I'm missing? Maybe it has something to do with encoding? Or maybe I must read the file differently (if that's the only way). Not sure. Any suggestions?
Edit: .pdf files work now after I added encoding. However .docx files still arrive blank. So the question about docx remains! I edited the code above with the changes I made.
EDIT 2: .docx files work! The file I used to test was incorrect and normal docx file it goes through fine! So problem solved. No need to resort to PHPMailer, although I did try it and it works well. I will either switch to PHPMailer now or use it when I need to add more functionality to the sending mechanism. Otherwise this little script is enough for simple emails with 1 attachment.
Use this, it's much easier, and tested:
http://www.phpclasses.org/package/32-PHP-A-class-for-sending-mime-email-.html
Both files now work fine. PDF files had to have encoding (base64) and after I added that they worked. Docx files always worked, but I used wrong file to test originally. That was causing the problem. So problem solved. There was no need to resort to PHPMailer, however I tried that as well and it works good too.

Apple Mail does not display PDF sent using Zend_Mail

My web application creates PDF documents using Zend_Pdf and sends them using Zend_Mail. It also attaches some user uploaded documents (also PDF). The attachments show up in all general used mail programs, except in Apple Mail. The created PDF is about 30 KB and the message is sent using an external mail server.
In Apple Mail the message list shows the message with a paper clip (indicating that it has attachments), but when the message is opened no attachments are visible. When I click 'Details' in the message head, it shows the attachments and the option to save them.
This is the (stripped down) code that sends the e-mail:
<?php
$mail = new Zend_Mail('utf-8');
$mail->setFrom('niels#example.com', 'Niels')
->setSubject('Subject')
->addTo('niels#example.com', 'Niels')
->setBodyHtml('Hi there', 'utf-8', Zend_Mime::ENCODING_8BIT);
$a = new Zend_Mime_Part($pdfContent);
$a->type = 'application/pdf';
$a->filename = 'my_pdf.pdf';
$a->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
$a->encoding = Zend_Mime::ENCODING_BASE64;
$mail->addAttachment($a);
$mail->setHeaderEncoding(Zend_Mime::ENCODING_BASE64);
$mail->send();
The mail I receive has the following header for the message
Content-Type: multipart/mixed; boundary="=_f6a669390c6713f60a851af814fe897f"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
MIME-Version: 1.0
The HTML mail content:
--=_f6a669390c6713f60a851af814fe897f
Content-Type: text/html; charset="utf-8"
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
The attachment content:
--=_f6a669390c6713f60a851af814fe897f
Content-Type: application/pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="my_pdf.pdf"
Is there a way that the attachments show up in the message in Apple Mail? Now some people respond with 'there are no attachments'. Does Apple do some 'smart' things to hide/show the attachments? Or should I use another Content-Disposition etc? I've searched quite some time to find a solution, but am running out of clues.
This is not Zend issue but Apple Mail issue. Install Thunderbird ;-)
Here are few tips:
problem like this can occur if you are sending inline files and attachments at the same time
mail app settings are defaulted to inline attachments
Close Mail
Open Terminal
enter command defaults write com.apple.mail DisableInlineAttachmentViewing -bool yes,
Open Mail and try again
you should not be explicitly specifying encoding in setting body, your mail is initialized with default 'UTF-8' encoding by the way you
you should not be encoding header unless you are sending emails in languages that use not Roman letters-based character set
Try attaching the file inline and
$mail = new Zend_Mail('utf-8');
$mail->setFrom('niels#example.com', 'Niels')
->setSubject('Subject')
->addTo('niels#example.com', 'Niels')
->setBodyHtml('Hi there');
// add attachment
$mail->createAttachment(file_get_contents('my_pdf.pdf'), 'application/pdf', Zend_Mime::DISPOSITION_ATTACHMENT , Zend_Mime::ENCODING_BASE64);
// try sending attachment inline... maybe this will work (not sure if supported by all mail clients)
// $mail->createAttachment(file_get_contents('my_pdf.pdf'), 'application/pdf', Zend_Mime::DISPOSITION_INLINE , Zend_Mime::ENCODING_BASE64);
$mail->send();
The answer that Alex provided was indeed the solution: it is an Apple Mail issue. When the attachment size increases, it shows up in the e-mail. For example: I just sent a PDF document that is bigger (79KB, shows up as 112KB in the message list) and that is visible. If I send the same kind of PDF (but smaller) it is hidden.

generating PDF on the fly using TCPDF

i'm using TCPDF library to generate a PDF (bill) on the fly and send it via email. It all works but i have a weird problem. When i send the email to a gmail account everything is fine, but when i send it to my mail server i get the email with the pdf but when i open it it doesn't open and i get a message "Adobe reader could not open file.pdf because it's either not a supported format or because the file has been damaged." (the pdf in the email is blank).
I save the PDF into a string like so:
$attachment = $pdf->Output("mypdf.pdf","E");
$attachment = chunk_split($attachment);
and send it via email like so:
$header .= "--".$separator.$eol;
$header .= "Content-Type: application/pdf; name='mypdf.pdf'".$eol;
$header .= "Content-Transfer-Encoding: base64".$eol;
$header .= "Content-Disposition= attachment".$eol.$eol;
$header .= $attachment;
i'm sending the email with php mail function.
The funny thing is if i force the download of the pdf, like so:
$attachment = $pdf->Output("mypdf.pdf","D");
the file is OK and opens without a problem! But if i change it back to "E" it doesn't work.
The other weird thing is that some times i can open the pdf (that i got on my mail server) without a problem, but the next time it wont work (even if i send the exact same email).
Does any one have any idea what is going on? I would like to avoid saving the pdf on the local server.
Why you avoid saving pdf file? You can save it with "F" parameter. After mail has sent you can delete it with unlink function
I see some minor flaws:
Content-Disposition= should be Content-Disposition:
You should end your attachment with "--".$separator."--"
I'm not sure, if this fixes your problems. Anyway I think it's quite complicated to create all the headers manually. I use PEARs Mail_Mime for this task since years and you will find a lot of simple ready to use solutions.

Sending mail with a Php with a pdf attachment

I'm trying to send an email from the php mail command. I've been able to what I've tried so far, but can't seem to get it to work with an attachment. I've looked around the web and the best code I've found led me to this:
$fileatt_name = 'JuneFlyer.pdf';
$fileatt_type = 'application/pdf';
$fileatt = 'JuneFlyer.pdf';
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
$data = chunk_split(base64_encode($data));
$MAEmail = "myemail#sbcglobal.net";
mail("$email_address", "$subject", "$message",
"From: ".$MAEmail."\n".
"MIME-Version: 1.0\n".
"Content-type: text/html; charset=iso-8859-1".
"--{$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" );
There are two problems when I do this. First, the contents of the email dissappear.
Second, there is an error on the attachment. "Adobe Reader could not open June_flyer.pdf because it is either not a supported file type or because the file has been damaged (for example it was sent as an email attachment and wasn't correctly decoded)"
Any ideas of how to deal with this?
Thanks,
JB
The very best way how to deal with mail and php is use a reliable well tested library - email with attachments can easily get very nasty. I personally recommend SwiftMailer.
may be problem is within header. if you want to learn the hard way then figure out how you can configure diffrent mimetypes with headers and do the stuff.
or else easy way is use PHPmailer or other email libraries which will do the hard part for you.
One process to learn the correct email format for sending attachments is to try sending yourself an email (with attachment) using Thunderbird, Outlook, etc.
Then view the source of that email. Try copying and pasting that message source into your PHP code (with a little trimming of headers like To and From and Subject that the mail() function already handles) and bada-bing, you have all you need right in front of you.
You can make it dynamic by replacing the chunks of stuff (HTML part, Text part, attachment) with your unique chunks or variables.
Then no fancy library is needed.

Categories