sending a pdf with fpdf with a attachment - php

morning all, my knowledge of php is very primitive so please excuse the code below
i am tying to creat and send a pdf with FPDF and have the ability to upload a file and send along with the pdf that fpdf creates.
i have the php code that sends the attachment and fpdf but its sending them in 2 separate emails, i want to combine the below so it sends everything in one email
this is my code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Attachment Without Upload - Excellent Web World</title>
<style>
body{ font-family:Arial, Helvetica, sans-serif; font-size:13px;}
th{ background:#999999; text-align:right; vertical-align:top;}
input{ width:181px;}
</style>
</head>
<body>
<form action="emailSend.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
<tr>
<th>Your Name</th>
<td><input name="fieldFormName" type="text"></td>
</tr>
<tr>
<tr>
<th>Your Email</th>
<td><input name="fieldFormEmail" type="text"></td>
</tr>
<tr>
<th>To Email</th>
<td><input name="toEmail" type="text"></td>
</tr>
<tr>
<th>Subject</th>
<td><input name="fieldSubject" type="text" id="fieldSubject"></td>
</tr>
<tr>
<th>Comments</th>
<td><textarea name="fieldDescription" cols="20" rows="4" id="fieldDescription"></textarea></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment" type="file"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send"><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
// download fpdf class (http://fpdf.org)
require("fpdf.php");
// fpdf object
$pdf = new FPDF();
// generate a simple PDF (for more info, see http://fpdf.org/en/tutorial/)
$pdf->AddPage();
$pdf->SetFont("Arial","B",14);
$pdf->Cell(40,10, "this is a pdf example");
// email stuff (change data below)
$to = "daniel.edwards#bourne-leisure.co.uk";
$from = "me#domain.com";
$subject = "send email with pdf attachment";
$message = "<p>Please see the attachment.</p>";
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "example.pdf";
// encode data (puts attachment in proper format)
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
// main header (multipart mandatory)
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol;
$headers .= "Content-Transfer-Encoding: 7bit".$eol;
$headers .= "This is a MIME encoded message.".$eol.$eol;
// message
$headers .= "--".$separator.$eol;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$headers .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$headers .= $message.$eol.$eol;
// attachment
$headers .= "--".$separator.$eol;
$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$headers .= "Content-Transfer-Encoding: base64".$eol;
$headers .= "Content-Disposition: attachment".$eol.$eol;
$headers .= $attachment.$eol.$eol;
$headers .= "--".$separator."--";
// send message
mail($to, $subject, "", $headers);
$to = $_POST['toEmail'];
$fromEmail = $_POST['fieldFormEmail'];
$fromName = $_POST['fieldFormName'];
$subject = $_POST['fieldSubject'];
$message = $_POST['fieldDescription'];
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $fromName";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent to: $to";
}
else{
echo "Error in Email sending";
}
?>
any help would be greatly appreciated

You can use PHPMailer script to do this job. Firstly, save your PDF in a file, and then use it in this script.
Example:
$oEmail = new PHPMailer();
$oEmail->From = 'you#domain.com';
$oEmail->addAddress( 'destination_address#domain.com' );
$oEmail->Subject = 'Subject';
$oEmail->Body = $bodytext;
$oEmail->addAttachment('path_to_your_file', 'name_of_file.ext');
return $oEmail->Send();

$to = "daniel.edwards#bourne-leisure.co.uk";
$from = "me#domain.com";
$subject = "send email with pdf attachment";
$message = "<p>Please see the attachment.</p>";
//$datei = "path to your pdf file you want to add as attachment";
$datei2 = "path to the uploaded file";
$boundary = strtoupper(md5(uniqid(time())));
//$f = file_get_contents($datei);
$f = $pdf->Output('','S');
$f2 = base64_encode($f);
$f3 = chunk_split($f2);
//$parts = explode('/',$datei);
//$file = $parts[count($parts)-1];
$file = "MyPdf.pdf";
$f_2 = file_get_contents($datei2);
$f_22 = base64_encode($f_2);
$f_23 = chunk_split($f_22);
$parts2 = explode('/',$datei2);
$file2 = $parts2[count($parts2)-1];
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-Type: multipart/mixed; boundary=$boundary";
$headers[] = "From: MyName <".$from.">";
$headers[] = "Reply-To: MyName <".$from.">";
$headers[] = "Subject: $subject";
$headers[] = "X-Mailer: PHP/".phpversion();
$headers[] = "--$boundary";
$headers[] = "Content-type: text/html; charset=\"utf-8\"";
$headers[] = "\n".$message;
$headers[] = "--$boundary";
$headers[] = "Content-Disposition: attachment; filename=$file";
$headers[] = "Content-Type: application/pdf; name=$file";
$headers[] = "Content-Transfer-Encoding: base64";
$headers[] = "\n".$f3;
$headers[] = "";
$headers[] = "--$boundary";
$headers[] = "Content-Disposition: attachment; filename=$file2";
$headers[] = "Content-Type: application/pdf; name=$file2";
$headers[] = "Content-Transfer-Encoding: base64";
$headers[] = "\n".$f_23;
$headers[] = "";
$headers[] = "--$boundary--";
$headers[] = "\n";
if( mail($to,$subject,'',implode("\n", $headers)) !== false )
{
echo "success";
}

Related

Sending attachment (.docx) with PHP mail();

while sending a mail using PHP mail() without attachment working fine.
But while sending with attachment sending Failed
please help me.
Whats wrong in my code?
Thanks in advance.
My HTML code is shown below
index.html
<html>
<head>
<title>Mail</title>
</head>
<body>
<form method="POST" action="mail.php" enctype="multipart/form-data">
<input type="text" name="fromName">
<input type="email" name="fromEmail">
<input type="file" name="fileAttach">
<input type="submit" name="submit">
</form>
</body>
</html>
The following is my Mail code
mail.php
<?php
if (isset($_POST['submit'])) {
/* $mailto = $_POST["mailTo"];*/
$mailto = "to#gmail.com";
$from_mail = $_POST["fromEmail"];
$replyto = $_POST["fromEmail"];
$from_name = $_POST["fromName"];
/*$message = $_POST["message"];*/
$message="This is message part";
/*$subject = $_POST["subject"];*/
$subject ="this is subject part";
$filename = $_FILES["fileAttach"]["name"];
$content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
$header .= "Reply-To: " . $replyto . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--" . $uid . "\r\n";
// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
$header .= "Content-type:text/html; charset=utf-8\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
// User Message you can add HTML if You Selected HTML content
$header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";
$header .= "--" . $uid . "\r\n";
$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"; // For Attachment
$header .= $content . "\r\n\r\n";
$header .= "--" . $uid . "--";
if (mail($mailto, $subject, $message, $header)) {
echo "<script>alert('Success');</script>"; // or use booleans here
} else {
//echo mysqli_error();
echo "<script>alert('Failed');</script>";
}
}
Is there anything to add or change in the code?

mail function not working properly

Can someone please help me with my mail function issue.
I want to receive text values in table and an attachment. Right now I am receiving the table code instead of the code output and the attachment.
And If I delete the modification I made for the attachment then I get the right output but only text.
<?php
include("config.php");
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$fn1 = $_POST['fn1'];
$fn2 = $_POST['fn2'];
$fn3 = $_POST['fn3'];
$fn4 = $_POST['fn4'];
$fn28= $_POST['fn28'];
$subject = 'test';
//get file details we need
$file_tmp_name = $_FILES['fn28']['tmp_name'];
$file_name = $_FILES['fn28']['name'];
$file_size = $_FILES['fn28']['size'];
$file_type = $_FILES['fn28']['type'];
$file_error = $_FILES['fn28']['error'];
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("vikas");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$email."\r\n";
$headers .= "Reply-To: ".$email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
$msg = "
<table border='1'>
<tbody>
<th>
<td><h3>Contact Information</h3></td>
</th>
<tr>
<td><b>Borrower's Full Name</b></td>
<td><span style='color:#F34536;'> $firstname $lastname </span></td>
</tr>
<tr>
<td><b>Email</b></td>
<td><span style='color:#F34536;'> $email</span></td>
</tr>
<tr>
<td><b>Attach Key Documents (optional)</b></td>
<td><span style='color:#F34536;'> $fn28</span></td>
</tr>
</tbody>
</table>
";
$msg1 = chunk_split(base64_encode($msg));
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= $msg1;
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
mail($toemail, $subject, $body, $headers)
?>
Is because you have this line:
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
All code is sent in text-plain, delete it and change it as text/html in $header:
$header .= 'MIME-Version: 1.0\r\n';
$header .= 'Content-type: text/html; charset=iso-8859-1\r\n';

Form data not sent in mail while attachment is sent in PHP

I am tyring to have a contact form on my website having option for visitor to send attachment with their information. I tried but couldn't succeed. The problem i am having is that the file is sent to the email but the form data and email subject is not sent with the attachment.
HTML:
<form name="form1" enctype="multipart/form-data" method="post" action="do_send.php">
<label>
<input type="text" name="name" id="name" />
</label>
<label>
<input type="text" name="age" id="age" />
</label>
<label>
<input type="email" name="email" id="email" />
</label>
<label>
<input type="file" name="my_file" />
</label>
<label>
<input type="submit" name="button" value="Submit" />
</label>
</form>
do_send.php:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
if($_POST && isset($_FILES['my_file']))
{
//get file details we need
$file_tmp_name = $_FILES['my_file']['tmp_name'];
$file_name = $_FILES['my_file']['name'];
$file_size = $_FILES['my_file']['size'];
$file_type = $_FILES['my_file']['type'];
$file_error = $_FILES['my_file']['error'];
if($file_error>0)
{
die('upload error');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
# Mail headers should work with most clients (including thunderbird)
$headers = "MIME-Version: 1.0\r\n";
$headers .= "X-Mailer: PHP/" . phpversion()."\r\n";
$headers .= "From:".$email."\r\n";
$headers .= "Subject:".$subject."\r\n";
$headers .= "Reply-To: ".$email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=".md5('boundary1')."\r\n\r\n";
$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: multipart/alternative; boundary=".md5('boundary2')."\r\n\r\n";
$headers .= "--".md5('boundary2')."\r\n";
$headers .= "Content-Type: text/plain; charset=ISO-8859-1\r\n\r\n";
$headers .= $MESSAGE_BODY."\r\n\r\n";
$headers .= "--".md5('boundary2')."--\r\n";
$headers .= "--".md5('boundary1')."\r\n";
$headers .= "Content-Type: ".$file_type."; ";
$headers .= "name=\"".$file_name."\"\r\n";
$headers .= "Content-Transfer-Encoding:base64\r\n";
$headers .= "Content-Disposition:attachment; ";
$headers .= "filename=\"".$file_name."\"\r\n";
$headers .= "X-Attachment-Id:".rand(1000,9000)."\r\n\r\n";
$headers .= $encoded_content."\r\n";
$headers .= "--".md5('boundary1')."--";
if ($_POST["email"]!='') {
$ToEmail = 'info#mywebiste.com';
$EmailSubject = 'Website contact form';
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br><br>";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br>";
$MESSAGE_BODY .= "Age: ".$_POST["age"]."<br>";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $headers) or die ("Failure");
echo "<script> alert('Messgae successfully sent!');
window.location='index.html'</script>";
return true;
} else{
echo "<script> alert('Temporary problem, try again!');
window.location='index.html'</script>";
}
}
?>
Kindly point out where i am doing mistake. I am in learning stage please help me solving this issue. Please guide me where to do amendment in the do_send.php so that the form data and email subject is also sent with the attachment.
<?php
$nom = $_POST['lastName'];
$prenom = $_POST['firstName'];
$from_email = $_POST['email']; //sender email
if($_POST && isset($_FILES['my_file']))
{
$recipient_email = 'youremail#exemple.com'; //recipient email
$subject = 'Inscription Etudiant'; //subject of email
$message = 'This is body of the message'; //message body
$message = 'Nom: '.$nom."\n";
$message .= 'Prenom: '.$prenom."\n";
$message .= 'Email: '.$from_email;
//get file details we need
$file_tmp_name = $_FILES['my_file']['tmp_name'];
$file_name = $_FILES['my_file']['name'];
$file_size = $_FILES['my_file']['size'];
$file_type = $_FILES['my_file']['type'];
$file_error = $_FILES['my_file']['error'];
$user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if($file_error>0)
{
die('upload error');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("YADIStudio");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$user_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
$sentMail = #mail($recipient_email, $subject, $body, $headers);
if ($sentMail) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message. We will contact you shortly.');
window.location = 'index.php';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to youremail#exemple.com');
window.location = 'index.php';
</script>
<?php
}
}
?>
<--! YADI Studio Agency Copyright 2015 -->

php - instead of uploading to folder, send as email with attachment of file uploaded

<?php
//if there is post
if(isset($_POST) && !empty($_POST)){
//if there is attachment
if(!empty($_FILES['attachment']['name'])){
//store some variables
$file_name = $_FILES['attachment']['name'];
$temp_name = $_FILES['attachment']['tmp_name'];
$file_type = $_FILES['attachment']['type'];
//get the extension of the file
$base = basename($file_name);
$extension = substr($base, strlen($base)-4,strlen($base));
//only these file type will be allowed
$allow_extensions = array(".doc","docx",".pdf",".zip",".png");
//check if file is allowes
if(in_array($extension,$allow_extensions)){
//mail essentials
$from = $_POST['email'];
$to = "sampleemail#gmail.com";
$replyto = $to;
$subject = "email with attachment";
$message = "this is a random message";
//things you need
$file = $temp_name;
$content = chunk_split(base64_encode(file_get_contents($file)));
$uid = md5(uniqid(time()));
//standard mail headers
$header = "From " . $from . "\r\n";
$header .= "Reply-To: " . $replyto . "\r\n";
$header .= "MIME-Version: 1.0\r\n";
//declairing we hav e multiple parts of message like text
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format. \r\n";
//plain text part
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
//file attachment
$header .= "--".$uid."\r\n";
$header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
$header .= $content. "\r\n\r\n";
//send mail
if(mail($to, $subject, "", $header)){
echo "Mail Sent";
}
else
{
echo "Failed";
}
}
else{
echo "file type not allowed";
}
}
else{
echo "no file posted";
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="text" name="email" value="from" />
<br>
<input type="file" name="attachment" />
<br>
<input type="submit" value="Send Mail" />
</form>
</body>
</html>
Can't find the bug to my code, I am not getting the link to my attachment.. T_T please help. I am not good in boundary.. T_T I tried using phpmailer but can't get it to work, is there any document to read on how to set it up? I really just wanted to make a simple form with attach button for applicant to sent their resumes..
Everything after $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n"; should be in a $body, not a header.
I would get rid of this: $header .= "This is a multi-part message in MIME format. \r\n";
After $content you actually need to put another line with the mime separator.
$body .= $content . "\r\n" . '--' . $uid . '--';
And finally
if (mail($to, $subject, $body, $header)) {...

PHP: Sending mails with attachment to email accounts from database

I have been trying to get an email form that will send emails with attachments to email adresses which are stored in a database. I already have a script that will send an email to the email adresses in my database and I have a script that sends 1 attachment to 1 email and both of them work fine. The problem however is that I can't get them combined into 1 script. I have tried to combine the 2 into 1 many times but I can seem to figure it out. Since I'm still a student I am still learning how to do these things.
I will post the code I have below to show you what I have so far. If anyone has any tips or could show me how to do it it would be very helpful.
config.php
<?php
$server="localhost";
$database="NAW";
$db_user="root";
$db_pass="something";
$fromadmin="test#test.com";
$table="Email";
$table_email="Email";
?>
Send mails to email adresses in database:
<?php
include "header.php";
include "config.php";
if( $_POST || $_FILES )
{
$seconds=$_POST['seconds'];
$subject=$_POST['subj'];
$messagesend=$_POST['message'];
mysql_connect($server, $db_user, $db_pass)
or die ("Database CONNECT Error");
$resultquery = mysql_db_query($database, "select * from $table");
while ($query = mysql_fetch_array($resultquery))
{
$emailinfo=$myemail;
$mailto=$query[$table_email];
mail($mailto, $subject, $messagesend , "From:".$fromadmin."\nReply-To:".$fromadmin."\n");
echo 'Mail sent to '.$mailto.'<br>';
sleep($seconds);
}
echo 'Mails sent. Go Back';
}
else
{
?>
<table height="250" cellpadding="1">
<tr><td valign="top">
<h2>Mail Sender</h2><br><form action="massmail.php" method="POST">
<div align="center">
<table cellpadding="0" border="0" align="left">
<tr>
<td>
Subject:
</td>
<td>
<input type="text" align="left" name="subj" size="66">
</td>
</tr>
<tr><td align="left" valign="top">
Message Text:</td><td align="left"> <textarea name="message" rows="15" cols="60" ></textarea></td></tr>
<tr>
<tr><td colspan="2" align="left">
Seconds between messages:<input type="text" size="10" name="seconds" value="0.1"> (seconds)
</td></tr>
<tr><td colspan="2">
<input type="submit" value="Send mass mails" name="submit" >
</Td>
</tr>
</table>
</div>
</td>
</tr>
</table>
<?php
}
include "footer.php";
?>
Send a mail with an attachment:
<?php
if( $_POST || $_FILES )
{
// email fields: to, from, subject, and so on
// Here
$from = "test#test.com";
$to = "test2#test.com";
$subject = "Mail with Attachment";
$message = "This is the message body and to it I will append the attachments.";
$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 = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
fixFilesArray($_FILES['attachment']);
foreach ($_FILES['attachment'] as $position => $file)
{
// should output array with indices name, type, tmp_name, error, size
$message .= "--{$mime_boundary}\n";
$fp = #fopen($file['tmp_name'],"rb");
$data = #fread($fp,filesize($file['tmp_name']));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".$file['name']."\"\n"."Content-Description: ".$file['name']."\n" ."Content-Disposition: attachment;\n" . " filename=\"".$file['name']."\";size=".$file['size'].";\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $from;
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return 1; } else { return 0; }
}
//This function will correct file array from $_FILES[[file][position]] to $_FILES[[position][file]] .. Very important
function fixFilesArray(&$files)
{
$names = array( 'name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);
foreach ($files as $key => $part) {
// only deal with valid keys and multiple files
$key = (string) $key;
if (isset($names[$key]) && is_array($part)) {
foreach ($part as $position => $value) {
$files[$position][$key] = $value;
}
// remove old key reference
unset($files[$key]);
}
}
}
?>
<html>
<body>
<form method="POST" action="bijlagetest.php" enctype="multipart/form-data">
<input type="file" name="attachment[]"><br/>
<input type="submit">
</form>
</body>
</html>
Ok to attach Files the User first needs an Upload-Form
<form enctype="multipart/form-data" action="uploader.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>
to save the File in PHP do something like this
$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!";
}
So now you have the Files to send as Attachment, rewrite your script to a function that can handle multiple attachments...
something like this should work...
<?php
function sendMail($to, $from, $subject, $message, $attachments){
$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($attachments);$x++){
$file = fopen($attachments[$x],"rb");
$data = fread($file,attachmentsize($attachments[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$attachments[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$attachments[$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>";
}
}
?>
I have not tested this code but it should push you in the right direction ;-)
Try This,
First create one folder temp.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
//Database credentials
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "reassurance";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");
$filename='temp/test.csv';
//$filename='temp/'.$test.'.csv';
$fp=fopen($filename,"w");
$sql = mysql_query("SELECT * FROM `contactus`");
$row=mysql_fetch_assoc($sql);
$seperator="";
$comma="";
foreach($row as $name =>$value)
{
$seperator.=$comma.''.str_replace('','""',$name);
$comma=",";
}
$seperator.="\n";
$seperator;
fputs($fp,$seperator);
mysql_data_seek($sql,0);
while($row=mysql_fetch_assoc($sql))
{
$seperator="";
$comma="";
foreach($row as $name =>$value)
{
$seperator.=$comma.''.str_replace('','""',$value);
$comma=",";
}
$seperator.="\n";
fputs($fp,$seperator);
}
fclose($fp);
$my_file ='test.csv';
$path = "temp/";
$from_name = "Hara Prasad Hota";
$from_mail = "haraprasad#lemonpeak.com";
$mailto = "haraprasad#lemonpeak.com";
$subject = "This is a mail with attachment.";
$message = "Hallo,\r\n do you got attachment? I hope it is working.\r\n\r\Hara";
$replyto="haraprasad#lemonpeak.com";
$file = $path.$my_file;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$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";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
mail($mailto, $subject, "", $header)
?>

Categories