attaching file to an email - php

I have this form to send an email and the visitor can send an attachment with his email as will everything gos well the email sent but the attachment comes to the email like this
if he uploaded any C.V the C.V will be attached to this Email
--_1_c4fe3315ccb7d6076c71d64ec5265ecc Content-Type:
multipart/alternative; boundary="_2_c4fe3315ccb7d6076c71d64ec5265ecc"
--_2_c4fe3315ccb7d6076c71d64ec5265ecc Content-Type: text/plain;
charset="UTF-8" Content-Transfer-Encoding: 7bit
--_2_c4fe3315ccb7d6076c71d64ec5265ecc--
--_1_c4fe3315ccb7d6076c71d64ec5265ecc Content-Type:
application/octet-stream; name="Yousef.txt"
Content-Transfer-Encoding: base64 Content-Disposition: attachment
--_1_c4fe3315ccb7d6076c71d64ec5265ecc--
I can see my attached file name but no attachment come with email
the HTML form
<form id="sendYourCV" method="post" action="<?php $_SERVER['PHP_SELF'] ?>" enctype="multipart/form-data"
class="padding_16px">
<div class="padding_16 clear_both">
<p class="f_right complaints_form"><label for="cSector">القطاع :</label></p>
<select name="cSector" id="cSector" class="styled-select f_right">
<?php
$getSections = $db->prepare("SELECT * FROM career_selection_sec_arabic");
$getSections->execute();
$res = $getSections->get_result();
while ($s = $res->fetch_object()) {
echo "<option value='$s->sector'>$s->sector</option>";
}
?>
</select>
</div>
<div class="padding_16 clear_both">
<p class="f_right complaints_form"><label for="cAdministration">الادارة :</label></p>
<select name="cAdministration" id="cAdministration" class="styled-select f_right">
<?php
$getSections = $db->prepare("SELECT * FROM career_selection_admin_arabic");
$getSections->execute();
$res = $getSections->get_result();
while ($a = $res->fetch_object()) {
echo "<option value='$a->admin'>$a->admin</option>";
}
?>
</select>
</div>
<div class="padding_16 clear_both">
<p class="f_right complaints_form"><label for="cBranch">الفرع :</label></p>
<select name="cBranch" id="cBranch" class="styled-select f_right">
<?php
$getSections = $db->prepare("SELECT * FROM career_selection_bran_arabic");
$getSections->execute();
$res = $getSections->get_result();
while ($s = $res->fetch_object()) {
echo "<option value='$s->branch'>$s->branch</option>";
}
?>
</select>
</div>
<div class="padding_16 clear_both">
<p class="f_right complaints_form"><label for="cCareer">الوظيفة :</label></p>
<select name="cCareer" id="cCareer" class="styled-select f_right">
<?php
$getSections = $db->prepare("SELECT * FROM career_selection_car_arabic");
$getSections->execute();
$res = $getSections->get_result();
while ($s = $res->fetch_object()) {
echo "<option value='$s->career'>$s->career</option>";
}
?>
</select>
</div>
<div class="padding_16 clear_both m_top_10px">
<p class="f_right complaints_form">الاسم :</p>
<input name="cName" type="text" class="form_textarea_rec f_right" placeholder="اسمك"/>
</div>
<div class="padding_16 clear_both m_top_10px">
<p class="f_right complaints_form">التليفون :</p>
<input name="cTelephone" type="text" class="form_textarea_rec f_right" placeholder="تليفونك"/>
</div>
<div class="padding_16 clear_both m_top_10px">
<p class="f_right complaints_form">الايميل :</p>
<input name="cEmail" type="text" class="form_textarea_rec f_right" placeholder="بريدك الالكتروني"/>
</div>
<div class="padding_16 clear_both m_top_10px">
<p class="f_right complaints_form">الرسالة :</p>
<span class="margin_49px">
<textarea name="cMessage" class="form_textarea_vertical_2 f_right m_left_6px" placeholder="رسالتك"
type="text"></textarea>
</span>
</div>
<div class="padding_16 clear_both m_top_10px">
<p class="f_right complaints_form"></p>
</div>
<div class="padding_16 clear_both m_top_10px">
<p class="f_right complaints_form">سيرتك الذاتية :</p>
<input type="file" name="upFile" id="upFile" class="f_right" style="direction:rtl;"/>
</div>
<input type="submit" name="submit" id="submit" class="btn_main m_bottom_18px m_left_286px"
value="ارسل"/>
</form>
this is my form code that I used
<?php
error_reporting(E_ALL | E_STRICT);
if (isset($_POST['submit'])) {
$sector = $_POST['cSector'];
$cAdministration = $_POST['cAdministration'];
$cBranch = $_POST['cBranch'];
$cCareer = $_POST['cCareer'];
$name = $_POST['cName'];
$telephone = $_POST['cTelephone'];
$cEmail = $_POST['cEmail'];
$cMessage = $_POST['cMessage'];
$recipient = 'info#test.com';
$subject = "Someone apply for career";
$myCv = $_FILES['upFile']['name'];
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['upFile']['tmp_name'])));
$boundary = md5(date('r', time()));
$content = "This information is for someone who apply for your new career\n
Sector Applied For:" . $sector . ",\n
Administration Applied For:" . $cAdministration . ",\n
Branch Applied For:" . $cBranch . ",\n
Career Applied For:" . $cCareer . ",\n
His Name Is: " . $name . ",\n
His Phone Number: " . $telephone . ",\n
His Message: " . $cMessage . ",\n
His Email: " . $cEmail . ",\n if he uploaded any C.V the C.V will be attached to this Email
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"UTF-8\"
Content-Transfer-Encoding: 7bit
--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$myCv\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
$headers = "From:info#test.com\r\nReply-To:info#test.com";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$sent = mail($recipient, $subject, $content, $headers);
if ($sent) {
header("Location:index.php?pid=17&carr=your message has been sent, we will contact you soon.");
} else {
echo "Error";
}
}
?>
I copied this code from some online tutorial but can't understand why it does not go will with the attachment
thanks in advance

Problem: I guess you are putting extra space for content-type declaration code in His mail:. See my code there is no need for spaces before that if you will give space it will produce error.
Now the working code with correct formatting is given below:
<?php
error_reporting(E_ALL | E_STRICT);
if (isset($_POST['submit'])) {
$sector = $_POST['cSector'];
$cAdministration = $_POST['cAdministration'];
$cBranch = $_POST['cBranch'];
$cCareer = $_POST['cCareer'];
$name = $_POST['cName'];
$telephone = $_POST['cTelephone'];
$cEmail = $_POST['cEmail'];
$cMessage = $_POST['cMessage'];
$recipient = 'info#test.com';
$subject = "Someone apply for career";
$myCv = $_FILES['upFile']['name'];
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['upFile']['tmp_name'])));
$boundary = md5(date('r', time()));
$content = "This information is for someone who apply for your new career\n
Sector Applied For:" . $sector . ",\n
Administration Applied For:" . $cAdministration . ",\n
Branch Applied For:" . $cBranch . ",\n
Career Applied For:" . $cCareer . ",\n
His Name Is: " . $name . ",\n
His Phone Number: " . $telephone . ",\n
His Message: " . $cMessage . ",\n
His Email: " . $cEmail . ",\n if he uploaded any C.V the C.V will be attached to this Email
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"UTF-8\"
Content-Transfer-Encoding: 7bit
--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$myCv\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
$headers = "From:info#test.com\r\nReply-To:info#test.com";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$sent = mail($recipient, $subject, $content, $headers);
if ($sent) {
header("Location:index.php?pid=17&carr=your message has been sent, we will contact you soon.");
} else {
echo "Error";
}
}
?>
I hope this will solve your problem. Since it worked for me with your HTML code.
Happy Coding!!!

function mailWithAttachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message, $totalmailsent)
{
$file = $path.$filename;
$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.">\n";
$header .= "Reply-To: ".$replyto."\n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\n\n";
$header .= "This is a multi-part message in MIME format.\n";
$header .= "--".$uid."\n";
$header .= "Content-type:text/html; charset=iso-8859-1\n";
$header .= $message."\n\n";
$header .= "--".$uid."\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\n\n";
$header .= $content."\n\n";
$header .= "--".$uid."--";
if(mail($mailto, $subject, "", $header))
{
return 1;
}
else
{
return 0;
}
}
You give this a try and let me if fixed, since I'm using this with native php mail

I used the following code along with swiftmailer to do the job.
function send_email_attachment($email, $name, $filename) {
//return $email; //exit;
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername('username')
->setPassword('password')
;
/*
You could alternatively use a different transport such as Sendmail or Mail:
// Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Mail
$transport = Swift_MailTransport::newInstance();
*/
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
$the_message = "Hi {$name},<br/> Your booking is CONFIRMED and the invoice pertaining to the booking is attached with this mail. <br/> ";
// Create a message
$message = Swift_Message::newInstance('Subject')
->setFrom(array('email' => 'name'))
->setTo(array($email => $name))
->setBody($the_message, 'text/html')
->attach(Swift_Attachment::fromPath($filename))
;
// Send the message
$result = $mailer->send($message);
//if ($result){ return 'DONE';}else{ return 'SORRY';}
return;
}
?>
This worked well when I used it for one of the sites which I helped in developing and I hope it will work for you too.
N. B.: You will need to get swiftmailer to make the code work.

Perhaps consider using a simplified library such as PHPMailer? It handles most of the parts that take you excessive time for you, you wouldn't need to add headers and all that - it's done for you.
Example:
$mail=new PHPMailer();
$mail->isSMTP();
//host through which the mail should be sent
$mail->Host="smtp.mydomain.com";
//address where the email is going to be sent from
$mail->From="me#mydomain.com";
//address where the email is going
$mail->AddAddress("person#otherdomain.com");
//subject for the email
$mail->Subject="Example Email";
//Your email will be displayed as HTML
$mail->IsHTML(true);
// you can use HTML here
$mail->Body="Hi, This <strong>is</strong> an email";
//base64 encoding is applied here by default
$mail->AddAttachment("path/to/file");
//send the email
if ($mail->Send())
{
echo "Mail Sent";
}
else
{
echo "Error sending mail: " . $mail->ErrorInfo;
}
I usually use code very similar to this without any problems. I hope this helps, and makes your life much simpler. Just remember to include the PHP mailer library in the script, see the tutorial here for info on that.

Hay #Mikky you just need to adjust you code try this
<?php
error_reporting(E_ALL | E_STRICT);
if (isset($_POST['submit'])) {
$position = $c;
$name = $_POST['cName'];
$telephone = $_POST['cTelephone'];
$cEmail = $_POST['cEmail'];
$myCv = $_FILES['upFile']['name'];
$strTo = 'info#test.com';
$strSubject = "Someone apply for career";
$strMessage = nl2br("This information is for someone who apply for your new career\r\n
Position Applied For:" . $position . ",\r\n
His Name Is: " . $name . ",\r\n
His Phone Number: " . $telephone . ",\r\n
His Email: " . $cEmail . " \r\n");
//*** Uniqid Session ***//
$strSid = md5(uniqid(time()));
$strHeader = "";
$strHeader .= "From:info#test.com\r\nReply-To:info#test.com";
$strHeader .= "MIME-Version: 1.0\n";
$strHeader .= "Content-Type: multipart/mixed; boundary=\"" . $strSid . "\"\n\n";
$strHeader .= "This is a multi-part message in MIME format.\n";
$strHeader .= "--" . $strSid . "\n";
$strHeader .= "Content-type: text/html; charset=utf-8\n";
$strHeader .= "Content-Transfer-Encoding: 7bit\n\n";
$strHeader .= $strMessage . "\n\n";
//*** Attachment ***//
if ($_FILES['upFile']['name'] != "") {
$strFilesName = $_FILES["upFile"]["name"];
$strContent = chunk_split(base64_encode(file_get_contents($_FILES["upFile"]["tmp_name"])));
$strHeader .= "--" . $strSid . "\n";
$strHeader .= "Content-Type: application/octet-stream; name=\"" . $strFilesName . "\"\n";
$strHeader .= "Content-Transfer-Encoding: base64\n";
$strHeader .= "Content-Disposition: attachment; filename=\"" . $strFilesName . "\"\n\n";
$strHeader .= $strContent . "\n\n";
}
$flgSend = #mail($strTo, $strSubject, null, $strHeader); // # = No Show Error //
if ($flgSend) {
header("Location:index.php?pid=17&msg=done");
} else {
echo "Cannot send mail.";
}
}
?>
let me know if it's working now with you

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?

php mail() function to send mail with an attachment

I have created two scripts for this HTML and a corresponding PHP.
HTML markup:
<html>
<body>
<form action="http://senindiaonline.in/admar/non-series-numbers-db.php" method="post" target="_blank" name="non_series_numbers_db" enctype="multipart/form-data">
<label for="emp-id">Employee ID: </label>
<input type="text" name="emp-id" id="emp-id" maxlength="15" style='text-transform:uppercase'/>
<br/>
<label for="no-csv">If you have a mobile number database in CSV file format upload that here: </label>
<input name="no-csv" id="no-csv" type="file" accept=".csv"/>
<br/>
<label for="no-xls">If you have a mobile number database in XLS (excel) file format upload that here: </label>
<input name="no-xls" id="no-xls" type="file" accept=".xls"/>
<br/>
<label for="no-xlsx">If you have a mobile number database in XLSX (excel) file format upload that here: </label>
<input name="no-xlsx" id="no-xlsx" type="file" accept=".xlsx"/>
<br/>
<input name="send" value="Send" type="submit" id="send"/>
</form>
</body>
</html>
PHP script:
<?php
error_reporting(0);
$email_to = 'senindiagroup#gmail.com';
$email_subject = "Non-Seriesed Mobile Number Database from Ad&Marketing Employee Panel of Sen India Online inc.";
$emp_id = $_POST['emp-id'];
$sub="Employee ID: $emp_id";
$bound_text = "jimmyPI23";
$bound = "--" .$bound_text. "\r\n";
$bound_last = "--" .$bound_text. "--\r\n";
$email_message .= "If you can see this MIME than your client doesn't accept MIME types! \r\n" .$bound;
$email_message .= "Content-Type: text/html; Charset=\"iso-8859-1\"\r\n" ."Content-Transfer-Encoding: 7bit\r\n\r\n" ."$sub\r\n" .$bound;
//getting temporary file location with name
$a=file_get_contents($_FILES['no-csv']['tmp_name']);
$b=file_get_contents($_FILES['no-xls']['tmp_name']);
$c=file_get_contents($_FILES['no-xlsx']['tmp_name']);
//getting original name of the file you uploaded
$name=$_FILES["no-csv"]["name"];
$name1=$_FILES["no-xls"]["name"];
$name2=$_FILES["no-xlsx"]["name"];
$email_message .= "Content-Type: {\"application/octet-stream\"}; \n" . "name=\"$name\ "\n" . "Content-Transfer-Encoding: base64\r\n" ."Content-Disposition: attachment; \n" . " filename=\"$name\ "\n"."\r\n" .chunk_split(base64_encode($a)).$bound;
mail($email_to, $email_subject, $email_message, $headers);
?>
The error is:
syntax error showing on line 31, attach file with mail command.
And the mail is not send. I solve this error with DreamWeaver suggestion. Then the mail is send, but the attachment is not included in the mail.
This is the example of sending multiple attachments in mail
<?php
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.com";
$subject ="My subject";
$message = "My message";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
?>
if you want simple solution use phpmailer library, that would be easy to use,easy to configure.

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