PHP - Retrieve And Echo Email Attachment Using Imap Help
I have spent nearly all day scouring Google for help on this and after trying numerous scripts unsuccessfully and reading up on imap functions but still getting nowhere as well as frying my brain l have had to accept defeat unless anyone of the many gifted coders here can help me out with a script they might have written and used.
many thanks Callum Similar TutorialsI seem to be having a difficult time saving the attachments to a folder on the server, all the examples I see show it to the browser, what I need to do is copy the attachment to a separate folder and do some processing on it. So far everything I get, then ftp to my desktop appears corrupt. It works I just can't seem to unzip the zipped attachments, any ideas? My Code: (Not mine, I used examples from the web and put it into a function) function get_attachments($message_number){ global $connection; $structure = imap_fetchstructure($connection, $message_number); $attachments = array(); if(isset($structure->parts) && count($structure->parts)) { for($i = 0; $i < count($structure->parts); $i++) { $attachments[$i] = array( 'is_attachment' => false, 'filename' => '', 'name' => '', 'attachment' => '' ); if($structure->parts[$i]->ifdparameters) { foreach($structure->parts[$i]->dparameters as $object) { if(strtolower($object->attribute) == 'filename') { $attachments[$i]['is_attachment'] = true; $attachments[$i]['filename'] = $object->value; } } } if($structure->parts[$i]->ifparameters) { foreach($structure->parts[$i]->parameters as $object) { if(strtolower($object->attribute) == 'name') { $attachments[$i]['is_attachment'] = true; $attachments[$i]['name'] = $object->value; } } } if($attachments[$i]['is_attachment']) { $attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1); if($structure->parts[$i]->encoding == 3) { // 3 = BASE64 $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']); } elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']); } } } } return $attachments; } Calling Code: $a = get_attachments(6); $fp = fopen($a[1]['filename'], 'w'); fwrite($fp, $a); fclose($fp); imap_fetchstructure is not returing information about attachments for certain e-mails after the mailbox is migrated to exchange 2010. Using IMAP protocol and was working fine until the migration from exchange 2007 to 2010. 99% of emails with attachments works fine, but few don't. I can replicate the issue when an attachment is sent from gmail accounts or some xerox devices to exchange 2010. The output of imap_fetchstructure (message has no body, only attachment) looks like below, as you can see, parts is returning null. I have tested it using imap-2006e and imap-4.7b libraries and produces same issues. Any ideas how to resolve the issue or debug this issue? Can also replicate the problem in Thunderbird 2.0.0.24 stdClass Object ( [type] => 1 [encoding] => 5 [ifsubtype] => 1 [subtype] => MIXED [ifdescription] => 0 [ifid] => 0 [ifdisposition] => 0 [ifdparameters] => 0 [ifparameters] => 1 [parameters] => Array ( => stdClass Object ( [attribute] => boundary [value] => AHNKAKBLDCDIDAGCDHGDAAAKACAK ) ) [parts] => Array ( ) ) I have a script that fetch emails and its work file when I call it through SSH with PHP at the beginning on the path when I added a cronjob it was working fine too... the problem start when I disable the cronjob email response, the script dose not functioning with Imap What can I do in order to bypass this problem, I will try to call it with include but I have no other options.. Please help Hi guys, I have written a script that opens up my gmail messages via IMAP stores them in an array. However, I have thousands of emails, so this is taking forever. Is there a faster way of doing this? Here's my code Code: [Select] <?php //lets get those emails /* connect to gmail */ $hostname = '{imap.gmail.com:993/imap/ssl}INBOX'; $username = 'info@***********.com'; $password = '******'; /* try to connect */ $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error()); /* grab emails */ $emails = imap_search($inbox,'ALL'); /* if emails are returned, cycle through each... */ if($emails) { /* for every email... */ foreach($emails as $email_number) { $message = imap_fetchbody($inbox,$email_number,2); } } /* close the connection */ imap_close($inbox); ?> I created a php file to send an email with two image attachments. The email portion sends the email o.k., but I can't get the attachments to load. The first is my form. <?php if(!empty($_POST)) { // The HTML form handler. require "handler.php"; } ?> <script type = "text/javascript"> //Validate required function validateRequired(FIELD, ALERTTEXT) { with(FIELD) { if(value == null || value == '') { alert(ALERTTEXT); return false; } else { return true; }; }; }; function validateForm(FORM) { with(FORM) { if(validateRequired( fName, "You must provide your First Name!") == false) {fName.focus(); return false;}; if(validateRequired( lName, "You must provide your Last Name!") == false) {lName.focus(); return false;}; if(validateRequired( job, "You must provide your Occupation!") == false) {job.focus(); return false;}; if(validateRequired( month, "You must provide your Birthday Month!") == false) {month.focus(); return false;}; if(validateRequired( day, "You must provide your Birthday Day!") == false) {day.focus(); return false;}; if(validateRequired( year, "You must provide your Birthday Year!") == false) {year.focus(); return false;}; if(validateRequired( city, "You must provide your City!") == false) {email.focus(); return false;}; if(validateRequired( state, "You must provide your State!") == false) {email.focus(); return false;}; if(validateRequired( phone, "You must provide your Phone Number!") == false) {email.focus(); return false;}; if(validateRequired( email, "You must provide your Email!") == false) {email.focus(); return false;}; //if(validateRequired( full, "You must provide a Full Body Photo!") == false) {full.focus(); return false;}; //if(validateRequired( hdst, "You must provide a Head Shot Photo!") == false) {hdst.focus(); return false;}; }; }; </script> <div id="form"> <p>STEP ONE:</p> <form name="contest" method="post" action="paypal.php" onsubmit="return validateForm(this)" enctype="multipart/form-data" style="margin-left:10px;" > <div id="aName"> First Name<span style="color:#F00;">*</span> <input type="text" name="fName" id="fName" style="width:150px;" /> Last Name<span style="color:#F00;">*</span> <input type="text" name="lName" id="lName" style="width:150px;" /> Occupation<span style="color:#F00;">*</span> <input type="text" name="job" id="job" style="width:150px;" /> </div> <div id="location"> Birthday<span style="color:#F00;">*</span> <input type="text" name="month" maxlength="2" id="month" style="width:30px;" /> / <input type="text" name="day" id="day" maxlength="2" style="width:30px;" /> / <input type="text" name="year" id="year" maxlength="2" style="width:30px;" /> City<span style="color:#F00;">*</span> <input type="text" name="city" maxlength="20" id="city" style="width:200px;" /> State<span style="color:#F00;">*</span> <input type="text" name="state" maxlength="2" id="state" style="width:30px;" /> Phone<span style="color:#F00;">*</span> <input type="text" name="phone" maxlength="14" id="phone" style="width:200px;" /> </div> <div id="con contact"> Email<span style="color:#F00;">*</span> <input type="text" name="email" id="email" style="width:200px;" /> Website <input type="text" name="web" id="web" style="width:200px;" /> Facebook <input type="text" name="facebook" id="facebook" style="width:200px;" /> </div> <div id="biog"> Why Should you be crowned Diva of the Year?<span style="color:#F00; font-size:12px;"> *Limit 350 words</span> <br /> <textarea name="bio" id="bio" cols="60" rows="10"></textarea> </div> <!--<div id="fileUpload"> <p style="color:#F00; font-style:italic; font-size:12px;">A picture with your application is required. A full length and headshot only. The image must be .jpg</p> Full Body Picture<span style="color:#F00;">*</span> <span style="color:#F00; font-size:12px;">(Max file size 2MB)</span> <br /> <input type="hidden" name="MAX_FILE_SIZE" value="102400" /> <input type="hidden" name="upload" value="upload" id="upload" > <input type="file" name="full" id="full" /> <br /> <br /> Head Shot Picture<span style="color:#F00;">*</span> <span style="color:#F00; font-size:12px;">(Max file size 2MB)</span> <br /> <input type="hidden" name="MAX_FILE_SIZE" value="102400" /> <input type="file" name="hdst" id="hdst" /> <input type="hidden" name="upload" value="upload" id="upload" > </div>--> <div id="marketing"> <input type="checkbox" name="news" id="news" checked="checked" /> Yes, Please sign me up to receive a monthly newsletter and other email from SizeSexyDivas </div> <div id="done"> <input type="submit" name="submit" value="Submit" id="submit" > </div> <div id="errorMessage"> <?php echo "<h3>". $error ."</h3>"; ?> </div> <span style="text-align:center; font-size:10px; color:#999;">For full contest "Rules and Regulations" on the SizeSexyDiva of the Year Contest Click <a href="rules.php" style="color:#900;">Here.</a></span> </form> </div> This is the function php on the handler.php page: <?php // Process form fields $fName = $_POST['fName']; $lName= $_POST['lName']; $job = $_POST['job']; $month = $_POST['month']; $day = $_POST['day']; $year = $_POST['year']; $age = ($month . " / " . $day . " / " . $year); $city = $_POST['city']; $location = ($city . ", " . $state); $state = $_POST['state']; $phone = $_POST['phone']; $email = $_POST['email']; $web = $_POST['web']; $facebook = $_POST['facebook']; $bio = $_POST['bio']; $bio = wordwrap($bio, 70); $news = $_POST['news']; $_POST['fName'] = htmlspecialchars(stripslashes($_POST['fName'])); $_POST['lName'] = htmlspecialchars(stripslashes($_POST['lName'])); $_POST['email'] = htmlspecialchars(stripslashes($_POST['email'])); $_POST['bio'] = htmlspecialchars(stripslashes($_POST['bio'])); $_POST['web']= htmlspecialchars(stripslashes($_POST['web'])); $_POST['facebook']= htmlspecialchars(stripslashes($_POST['facebook'])); $_POST['city']= htmlspecialchars(stripslashes($_POST['city'])); $_POST['state']= htmlspecialchars(stripslashes($_POST['state'])); $_POST['month']= htmlspecialchars(stripslashes($_POST['month'])); $_POST['day']= htmlspecialchars(stripslashes($_POST['day'])); $_POST['year']= htmlspecialchars(stripslashes($_POST['year'])); if($_SERVER['REQUEST_METHOD']=="POST") { //Add a multipart boundary above the plain message $to = 'Del*Nique Works <customerservice@delnique.com>'; $to = 'SizeSexyDivas <contest@sizesexydivas.com>'; $from = stripslashes($fName . " " . $lName . " at " . $email); $subject = "Contestant Application " .strftime("%T", time()); // generate a random string to be used as the boundary marker $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x"; // Add the headers for a file attachment $head = "From: $from\n". "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // here, we'll start the message body. this is the text that will be displayed in the e-mail $application = "SizeSexyDiva of the Year Contestant: $from\n\n"; $application .= " Name: $fName" . " " . "$lName \n Occupation: $job \n Location: $location \n Phone: $phone \n Age: $age \n Email: $email \n Website: $web \n Facebook: $facebook\n Newsletter: $news\n Full Body: $fdata\n Head Shot: $hdata\n Bio: $bio \n\n "; //next, we'll build the invisible portion of the message body *note that we insert two dashes in front of the MIME boundary when we use it $application = "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" . $application ."\n\n"; //now we'll process our uploaded files foreach($_FILES as $userfile){ //store the file information to variables for easier access $tmp_name = $userfile['tmp_name']; $type = $userfile['type']; $name = $userfile['name']; $size = $userfile['size']; // if the upload succeded, the file will exist if (file_exists($tmp_name)) { // check to make sure that it is an uploaded file and not a system file if (is_uploaded_file($tmp_name)) { //open the file for a binary read the file to be attached ('rb' = read binary) $file = fopen($tmp_name,'rb'); // read the file content into a variable $data = fread($file,filesize($tmp_name)); // close the file fclose($file); // Base64 encode the file data for full and split it into acceptable length lines $data = chunk_split(base64_encode($data)); } $application .= "--{$mime_boundary}\n" . "Content-Type: {$type};\n" . " name=\"{$name}\"\n" . "Content-Disposition: attachment;\n" . " filename=\"{$fileatt_name}\"\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; } } // here's our closing mime boundary that indicates the last of the message $application .= "--{$mime_boundary}--\n"; //send mail function @mail( $to, $subject, $head, $application); ?> So if you can help me I would really appreciate it. Ive been trying to get this email attachment to work but I think one of the headers is wrong. It wont attach the file Code: [Select] $address = "mail@site.com"; $subject = "Test HTML Message"; $hash = md5(rand().time()); $headers .= "From: yourname <you@youremail.com>\r\nReply-To: noreply@youremail.com"; $headers .= "\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"bound-{$hash}\" "; $file = "http://www.site.com/images/funny.jpg"; $attachment = chunk_split(base64_encode(file_get_contents($file))); $ext = pathinfo($file, PATHINFO_EXTENSION); $file_base = pathinfo($file, PATHINFO_BASENAME); $body = " --bound-{$hash} Content-Type: text/html Content-Transfer-Encoding: 7bit <h2>Hello from Wizecho!</h2> <p>This is the actual email you will receive with <b>HTML</b> <i>formatting.</i></p> --bound-{$hash} Content-Type: image/jpeg name=\"{$file_base}\" MIME-Version: 1.0 Content-Transfer-Encoding: base64 Content-Disposition: attachment {$attachment} --bound-{$hash}-- "; if(mail($address,$subject,$body,$headers)){ echo "Email Sent"; }else{ echo "Mail not sent"; } Hi I need to attach a file to an email from my database records So far i have: function sendNewCandidate($user, $email, $agent, $jobtitle, $useremail, $cv) { $from = "From: ".$user." <".$useremail.">"; $subject = "New applicant"; $attachment = chunk_split(base64_encode(file_get_contents('http://www.website.co.uk/$cv'))); $body = $agent.",\n\n" ."".$user." has applied for your job ".$jobtitle."." ."We suggest you go to your admin panel and view the CV" ."- Thank you. "; return mail($email, $subject, $body, $from); } }; $cv holds the location of the file for the user. These files are generally .doc I have read i may need something like this: Content-Type: application/zip; name="attachment.zip" Content-Transfer-Encoding: base64 Content-Disposition: attachment but how would i incorporate this? Thanks guys Hello, im new here, and i have little experience to php and mysql as i started for 2 weeks ago. I started out with some tutorials and feeling im getting the hang of it. Enough of me, lets get to the point: <?php $con = mysql_connect('localhost',$user,$pass)or die(mysql_error()); $selectdb = mysql_select_db($selectdb)or die(mysql_error()); $sql = "SELECT * From table"; $result = mysql_query($sql); $num = mysql_num_rows($result); $myarray = array($result); $i =0; while ($i < $num){ echo $myarray[$i]; $i++; } ?> Here i have written a dummyscript that does what the original script does, it tries to fetch the keys from the table and then trying to loop it and echo out the results. The output in the browser is this: Resource id #3 I know this probably is a simple fix but i cant seem to get it sorted out. Hope some of you could help me get this baby work, or maybe have another way of doing it more "simple". Thanks in advance! Dan-Levi I have an operational database I built with PHPRunner software that works flawlessly...for the most part. I want to add functionality for a button which, once pressed will generate a "Print" copy of the current record as it appears in PHP from the actual web page. I don't mind if the content is attached in PDF, HTML, or any other form as long as the "Print" output looks the same as if it were actually printed on paper. The goal is to provide a method for users to simply click a button to send an email copy of the electronic information for the customer's records. I already have a field within the form that contains the customer's email address, so I can have the script pull that email and automatically use that. I just need the script to automatically attach the PDF copy or HTML copy (not sure which would be easier). It seems to me that if there were a way to have the "Print" command generate the copy then attach that generated copy instead of sending it to the "Print" dialog for the web browser, that would be easiest to then somehow attach to the email to be sent. I have scoured the web trying to find an option for this and only now have appealed to the experts on this forum for a possible resolution.
Hi, I have setup a standard contact form that sends an email using php "mail" function in my new website. Today, I received an email from a potential client through my website. However, unfortunately, I did not receive the user's email address because (as I discovered after wards), there was a syntax problem in the function, so all I received is their name and message. I am certain that the user has entered their email address because the form has validation, it just didn't send me the address so I have no way to contact that client... Is there a way to retrieve the lost email address from the server somehow? Thanks in advance Hi, I have a database that stores pdf files. I need to know how do I retrieve the pdf file from the database and then add it as an attachment to be emailed. Regards Dieter Hi, I've created a basic form which uploads a document to my server. How do I generate an email with the uploaded document as an attachment? Here's the HTML: <form enctype="multipart/form-data" action="form1.php" method="POST"> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadedfile" type="file" /><br /> <input type="submit" value="Upload File" /> </form> Here's the PHP: <?php $target_path = "uploads/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?> Thanks in advance! I'm pretty new to PHP, and by new, I mean I have never done it or any other form of coding before starting my job a month or so ago. I've basically been manually trying to pick up PHP as I go. The website that I am working on had its core built, but I am trying to add functionality to it. The website already had the contact for that you can see he http://www.janova.us/index.php/contact The form would submit an email to an email address based on which subject was picked. I have since added a simple file upload field. My problem, however, is tying in the form to the email. I need to upload it and then send it as an attachment with the email. Here is what I am working with currently: <div id="breadCrumbs"> <a href="index.php">MAIN</a> > <a href="index.php/contact">CONTACT</a> </div> <? $user =& JFactory::getUser(); $user_id = $user -> get('id'); $user_name = $user -> get('name'); $db = JFactory::getDBO(); $query = "SELECT jos_content.introtext, jos_content.fulltext FROM jos_content WHERE catid = 68 AND sectionid = 5 LIMIT 0,3"; $db->setQuery($query); $rows = $db->loadRowList(); ?> <div id="contactTop"> <div id="contactBanner"></div> <div id="contactInfo"> <? echo $rows[0][0]; echo $rows[0][1]; ?> </div> </div> <div id="contactGreeting"> <? echo $rows[1][0]; echo $rows[1][1]; ?> </div> <? if($user_id > 0) { $query = "SELECT jos_users.name, jos_users.email FROM jos_users WHERE id = ".$user_id; $db->setQuery($query); $user_data = $db->loadRow(); } if(isset($_POST["submit"])) { $error = false; $subjectError = false; $messageError = false; $nameError = false; $emailError = false; if(!isset($_POST["subject"]) || empty($_POST["subject"])) { $error = true; $subjectError = true; } if(!isset($_POST["message"]) || empty($_POST["message"])) { $error = true; $messageError = true; } if(!isset($_POST["name"]) || empty($_POST["name"])) { $error = true; $nameError = true; } if(!isset($_POST["email"]) || empty($_POST["email"])) { $error = true; $emailError = true; } else if(!ereg("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$",$_POST["email"])) { $error = true; $emailError = true; echo $_POST["email"]; } if(!$error) { $to = $_POST["subject"]."@janova.us"; $from = $_POST["email"]; $subject = $_POST["subject"]." by: ".$_POST["name"]; $message = $_POST["subject"]."\n\r\n\r".$_POST["message"]."\n\r\n\r-".$_POST["name"]; $headers = "From: $from"; <!----------BEGIN ADDED CODE-------------------------> // Obtain file upload vars $fileatt = $_FILES['fileatt']['tmp_name']; $fileatt_type = $_FILES['fileatt']['type']; $fileatt_name = $_FILES['fileatt']['name']; if (is_uploaded_file($fileatt)) { // Read the file to be attached ('rb' = read binary) $file = fopen($fileatt,'rb'); $data = fread($file,filesize($fileatt)); 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 .= "\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; 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"; } <!-----------END ADDED CODE----------------> mail($to,$subject,$message,$headers); echo "Your request has been submitted."; } else { ?> <form action="#" id="contactForm" method="post"> <div id="contactFormLeft"> <? if($user_id > 0) { ?> <label> Your name<? if($nameError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="name" value="<?=$user_data[0];?>"/><br/> <label> Your email<? if($emailError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="email" value="<?=$user_data[1];?>"/><br/> <? } else { ?> <label> Your name<? if($nameError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="name" value="<?=$_POST["name"];?>"/><br/> <label> Your email<? if($emailError) { ?><span class="formError">*</span><? }?> </label><br/> <input type="text" name="email" value="<?=$_POST["email"];?>"/><br/> <? } ?> <label> Subject<? if($subjectError) { ?><span class="formError">*</span><? }?> </label><br/> <select name="subject"> <option value="support" <? if($_POST["subject"]=="support") { echo "selected ";}?>>Support</option> <option value="training" <? if($_POST["subject"]=="training") { echo "selected ";}?>>Training</option> <option value="hr" <? if($_POST["subject"]=="hr") { echo "selected ";}?>>HR</option> <option value="sales" <? if($_POST["subject"]=="sales") { echo "selected ";}?>>Consultation</option> </select> <br/> <input type="submit" id="submit" name="submit" value=""/><br/> </div> <div id="contactFormRight"> <label> Message<? if($messageError) { ?><span class="formError">*</span><? }?> </label><br/> <textarea name="message"><?=$_POST["message"];?></textarea><br/> </div> </form> <? } } else { ?> <!--Request More Info AKA Contact Page--> <!--Intro Text from Article--> <form action="#" id="contactForm" method="post"> <div id="contactFormLeft"> <? if($user_id > 0) { ?> <label> Your name </label><br/> <input type="text" name="name" value="<?=$user_data[0];?>"/><br/> <label> Your email </label><br/> <input type="text" name="email" value="<?=$user_data[1];?>"/><br/> <? } else { ?> <label> Your name </label><br/> <input type="text" name="name" value="<?=$_POST["name"];?>"/><br/> <label> Your email </label><br/> <input type="text" name="email" value="<?=$_POST["email"];?>"/><br/> <? } ?> <label> Subject </label><br/> <select name="subject"> <option value="support" <? if($_POST["subject"]=="support") { echo "selected ";}?>>Support</option> <option value="sales" <? if($_POST["subject"]=="sales") { echo "selected ";}?>>Consultation</option> <option value="training" <? if($_POST["subject"]=="training") { echo "selected ";}?>>Training</option> <option value="hr" <? if($_POST["subject"]=="hr") { echo "selected ";}?>>HR</option> </select> <br/> <input type="submit" id="submit" name="submit" value=""/> </div> <div id="contactFormRight"> <label> Message </label><br/> <textarea name="message"><?=$_POST["message"];?></textarea><br/> <!-----------ADDED FILE UPLOAD BOX ------------------> <label> Attach File: </label> <br/> <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> <input type="file" name="fileatt" /> <br/> <!------------END FILE UPLOAD BOX---------------------> </div> </form> <? } ?> I have commented the changes I have added to the original code so that you can see what I have done. Any input on this would be greatly appreciated. Thanks. Interested to find out why this code doesn't seem to properly send the attachment.. it's driving my insane ? Code: [Select] <?php //define the receiver of the email $to = 'youraddress@example.com'; //define the subject of the email $subject = 'Test email with attachment'; //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: webmaster@example.com\r\nReply-To: webmaster@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('attachment.zip'))); //define the body of the message. ob_start(); //Turn on output buffering ?> --PHP-mixed-<?php echo $random_hash; ?> Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Hello World!!! This is simple text email message. --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: 7bit <h2>Hello World!</h2> <p>This is something with <b>HTML</b> formatting.</p> --PHP-alt-<?php echo $random_hash; ?>-- --PHP-mixed-<?php echo $random_hash; ?> Content-Type: application/zip; name="attachment.zip" Content-Transfer-Encoding: base64 Content-Disposition: attachment <?php echo $attachment; ?> --PHP-mixed-<?php echo $random_hash; ?>-- <?php //copy current buffer contents into $message variable and delete current output buffer $message = ob_get_clean(); //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"; ?> Does anyone know of a way to use PHP to create and email a HTML file? I was attempting to use the standard PHP mail function to pass a HTML string to the message variable, but mail clients have a pretty hard time rendering HTML/CSS correctly. My thought was, if I could take my HTML string and turn it into a file and attach it to a email message the user would be able to open the file in there default browser which would render without issues. Just for the record my HTML string also contains PHP variables, so it must be processes before being sent. So far my research suggests using the PEAR library for sending mail with attachments, but I am only finding literature on how to attach a file already existing on the server to an email message. I am having trouble finding a way to create a HTML file on the fly and attach it to an email message. Has anyone had a similar problem? Is there a different way to accomplish what I am attempting to do here? I am building a website that allows a client to email me documents (DocX, PDF, TXT,ZIP, etc) along with a simple HTML based form. I used DreamWeaver to create the form and the upload area. I figured out how to script the PHP code to send the text fields to my email address (and validate them), but I can't figure out how to get the attachments to send. I am BRAND NEW to PHP and just trying to figure all thing out. Any help would be appreciated. I have attached two .txt files to this post. One is the HTML code for the forum and one is the actual PHP code I am using to send the form to my email. Thanks for your help! [attachment deleted by admin] I am attempting to get my email form with file attachment to work. Apparently the file is not reaching getting to the validation portion of the page I have switched $_FILES['X'] on line 203 from file to fakefile as they are labeled in the form also I am employing css hacks to change the input file upload field to have a custom button example -> http://visualrealityink.com/dev/clients/arzan/snell_form_final/form.php here is my code I appreciate any help Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <style> #form_container{ display:block; position:absolute; width:610px; min-height:450px; background:#f8f8f8; padding: 5px 5px 5px 5px; font-family:Arial, Helvetica, sans-serif; font-size:14px; } #form { min-height:450px; width:100%; background:#ececec; padding:0 0 0 0; } #formheader { background:url(images/form2_08.png) no-repeat #2f2f2f; margin:0 0 0 0; padding:0 0 0 0; width:631; height:30px;} form{margin:35px 0 0 35px;} fieldset div { margin:0.3em 0; clear:both; } label { float:left; width:10em; text-align:left; margin-right:1em; font-family:Arial, Helvetica, sans-serif; font-size:14px; } input { padding:0.15em; margin:0 0 0 -110px; width:300px; background:url(images/inputbg.png) no-repeat; border:0px solid #ddd; background:#fafafa; -moz-border-radius:0.4em; -khtml-border-radius:0.4em; } .bg2{background:url(images/inputbg.png) no-repeat; height:28px; line-height:28px;} fieldset { border:0px solid #ddd; padding:0 0.5em 0.5em; margin:0 0 0 -100px; } #details{font-size:10px;} #logo{background:url(images/form2_11.png) no-repeat; width:189px; height:238px; margin:-200px 0 0 400px; position:absolute;} #submit{margin:14px 0 0 -5px; border:none; position:absolute; cursor:pointer; cursor:hand;} #reset{border:none; margin:14px 0 0 115px; position:absolute; cursor:pointer; cursor:hand; } #divinputfile{ background:url(images/form2_27.png) no-repeat 100% 1px; height:43px; line-height:43px; width:340px; }#divinputfile #filepc{ opacity: 0.0; -moz-opacity: 0.0; filter: alpha(opacity=00); font-size:18px; margin:0 0 0 0; cursor:hand; cursor:pointer; } #fakeinputfile{ margin-top:-28px; } #fakeinputfile #fakefilepc{ background:url(images/inputbg2.png) no-repeat; style:none; width:240px; height:28px; line-height:28px; border:0; margin:5px 0 0 0; font-size:18px; font-family:Arial; } button { cursor: hand; cursor: pointer; padding: 0px; margin: 0 0 0 0; } a.link_button{ cursor: hand; cursor: pointer; } .fileupload{ margin:0 0 0 50px; } input[type="file"] { cursor: pointer; } .error{font-size:9px; font-family:Arial, Helvetica, sans-serif; color:#F00; } .error ul { text-decoration: none; list-style: none; } .error li { color: #F00;} .captcha_form { margin: 0 0 0 -45px; width:235px; } #captchaimage{ padding:0 0 10px 0;} .small { font-size:9px;} </style> </head> <body> <?php if ($_POST['_submit_check']) { // If validate_form( ) returns errors, pass them to show_form( ) if ($form_errors = validate_form()) { show_form($form_errors); } else { // The submitted data is valid, so process it process_form(); } } else { // The form wasn't submitted, so display show_form(); } function show_form($errors = '') { // If the form is submitted, get defaults from submitted parameters if ($_POST['_submit_check']) { $defaults = $_POST; } else { // Otherwise, set our own defaults: medium size and yes to delivery $defaults = array('IssueDate' => '','ExpiryDate' => ''); } if ($errors) { $error_text = 'You need to correct the following errors:'; $error_text .= '<br /><ul>'; $error_text .= implode('<li>',$errors); $error_text .= '</li></ul>'; } else { // No errors? Then $error_text is blank $error_text = ''; } include 'formhelpers.php' ?> <div id="form_container"> <div id="form"> <br /> <div id="formheader"> </div> <form method="POST" action="<?php print $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data"> <span class="error"> <?php print $error_text ?> </span> <input type="hidden" name="_submit_check" value="1"/> <div> <label for="name">Name: </label> <?php input_text('name', $defaults) ?> </div> <div> <label for="email">Email:</label> <?php input_text('email', $defaults) ?> </div> <div> Attach Resume: <span class="small">(1MB : PDF : DOC : DOCX : TXT)</span> </div> <div> <!--<input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> <label for="userfile"></label> <input type="file" name="userfile" id="userfile"/> </div>--> <div id="divinputfile"> <input name="file" type="file" size="30" id="filepc" onchange="document.getElementById('fakefilepc').value = this.value;"/> <div id="fakeinputfile"> <input name="fakefile" type="text" class="link_button" id="fakefilepc" /> </div> </div> <div id="captchaimage"><img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" /></div> <div><label for="email"><a style="text-decoration: none" href="#" onclick="document.getElementById('captcha').src = 'securimage/securimage_show.php?' + Math.random(); return false">New Captcha: </a></label> <input type="text" name="captcha_code" class="captcha_form" size="10" maxlength="6" /> </div> <button type="submit" value="submit" id="submit" ><img src="images/form2_33.png" /></button> <button type="reset" value="reset" id="reset" ><img src="images/form2_37.png" /></button> </form> </div> <div id="logo"></div> </div> </div> <?php } function validate_form() { $errors = array( ); // name is required if ($_POST['name'] == "") { $errors[ ] = 'Please enter your name.'; } if (! strlen(trim($_POST['email']))) { $errors[ ] = 'Please enter your Email.'; } if (! preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $_POST['email'])) { $errors[ ] = 'Please enter a valid e-mail address'; } $filename=$_FILES['file']['name']; //For size if($_FILES["file"]["size"]>1000000) //1 mb { $errors[ ] = "File size should be less than 1MB"; } // for extention $ext = end(explode('.', $filename)); if($ext=='doc' || $ext=='txt' || $ext=='pdf' || $ext=='docx' ) { echo "write the code to upload file"; $max_allowed_file_size = 1024; // size in KB $name_of_uploaded_file = basename($_FILES['file']['name']); //get the file extension of the file $type_of_uploaded_file = substr($name_of_uploaded_file, strrpos($name_of_uploaded_file, '.') + 1); $size_of_uploaded_file = $_FILES["file"]["size"]/1024;//size in KBs //copy the temp. uploaded file to uploads folder $upload_folder = 'upload/'; $path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; $tmp_path = $_FILES["file"]["tmp_name"]; if(is_uploaded_file($tmp_path)) { if(!copy($tmp_path,$path_of_uploaded_file)){ echo 'error while copying the uploaded file'; die(); } } } else { $errors[ ] = "Only doc or pdf or txt file is allowed: $filename "; } return $errors; } function process_form() { $image = "http://www.visualrealityink.com/dev/clients/arzan/snell_form/images/email.png"; include_once('Mail.php'); include_once('Mail_Mime/mime.php'); $to = 'george@visualrealityink.com'; $text = $image . "<br />" . $values['name'] . "submitted a resume on our website. Please review the applications and contact the candidate if their resume is a fit for any open opportunities with the company. <br><br> Thank you. <br><br> SEI Team"; $message=new Mail_mime(); $message=setTXTBody($text); $message=addAttachment($path_of_uploaded_file); $body = $message->get(); $extraheaders = array("From"=>$formValues['email'], "Subject"=>$subject, "Reply-To"=>$formValues['email']); $headers = $message->headers($extraheaders); $mail = Mail::factory("mail"); $mail->send($to, $headers, $body); echo "email sent"; } ?> </body> </html> I'm trying to after submission
1. create a csv
2. insert record into db
3. send email that's created in form submission - $msg.
4. send email with attachment to only the email I specify (if possible)
if not attach it to the email that's created at submission.
I've search and search and found different methods but doesn't work with my code.
I kept 3 lines at the top but can't get them to work ... either I don't get an email after submission or don't get an attachement.
Can some one help?
<?php $random_hash = md5(date('r', time())); $csvString = "..."; // your entire csv as a string $attachment = chunk_split(base64_encode($csvString)); $to = "email@email.com"; if(isset($_POST['submit'])) { // VALIDATION if(empty($_POST['firstName'])) { "First Name Required"; } if(empty($_POST['lastName'])) { "Last Name Required"; } if(empty($error)) { $to = "$to"; $subject = 'The Form'; $headers = "MIME-Version: 1.0 \r\n"; $headers .= "Content-Type: text/html; \r\n" ; $msg .="<html> <head></head> <body> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td>This is the email sent.</td></tr> </table> </body> </html>"; include('con.php'); $con = mysqli_connect($host,$user,$pass,$dbName); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"thetable"); $firstName = mysqli_real_escape_string($con, $_POST['firstName']); $lastName = mysqli_real_escape_string($con, $_POST['lastName']); $sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'"; $result = mysqli_query($con,$sql); if(($result->num_rows)>= 1) { $theerror = "You exist"; } else { $sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'"; $success = "Sent ... Insert it!!!"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } $result = @mail($to, $subject, $msg, $headers); } mysqli_close($con); { } } } ?> Edited by barkly, 27 October 2014 - 02:59 PM. I would like to store PDF file into mysql (this part works) and then send it as email attachment and it should be retrieved from mysql table. Here's the code I have for now, but what it gives me is 0bytes large PDF file Saving PDF to mysql (it works), because size of blob in mysql table is OK. $fp = fopen('generated.pdf', 'r'); $content = fread($fp,filesize('generated.pdf')); $content = addslashes($content); fclose($fp); $DB->Query('insert into pdf_files (pdf_file, name) values ("'.$content.'", "'.$name.'")'); And here's the mailing part <?php $query = "SELECT name, pdf_file FROM pdf_files $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array ( $result)) { $fileContent =$row['pdf_file']; $fileName=$row['name']; } $fileatt = $fileContent; // getting file $fileatt_type ="application/pdf"; //type of file $fileatt_name = "attachment.pdf"; // name $fileatt_size = $fileSize; $email_from = "dont@have.it"; // mail from $email_subject = "Testtt"; // subject $email_message = "Testtt.<br>"; $email_message .= "Testtt.<br>"; // Message $email_to = $mail_user; // users mail $headers = "From: ".$email_from; $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}\""; $email_message .= "Testtt.\n\n" . "--{$mime_boundary}\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $email_message .= "\n\n"; $data = chunk_split(base64_encode($data)); $email_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"; $ok = @mail($email_to, $email_subject, $email_message, $headers); if($ok) { echo "<font face=verdana size=2><center>Mail was sent</center>"; } else { die("Error!"); } ?> |