PHP Email content arriving as attachment - php

I have this piece of PHP code, although it works, but the problem is that the email message content is sent as an attachment along with the intended attachment which means that when the email arrives, the body is blank but there's two attachments. One is the intended attachment and the other is the email content that is supposed to be displayed in the the email. Is there something I'm doing wrong?
Here's the full source code:
<?php
require('fpdf/fpdf.php');
include('./config.php');
$pdf = new FPDF('P', 'pt', 'Letter');
$pdf->SetAutoPageBreak(true, $margin);
$pdf->AddPage();
$pdf->SetFont('arial','',12);
if(isset($_POST['accept'])){
$id = $_POST['id'];
$to = 'me#somewhere.com';
$subject = urldecode($_POST['subject']);
$message = urldecode($_POST['message']);
$data = '';
$result = mysql_query("select * from applications where id = $id");
$row = $data_array = mysql_fetch_assoc($result);
$data .= "Name: " . $row['name'] . " \n\n";
$data .= "Surname: " . $row['surname'] . "\n\n";
$data .= "Age: ". $row['age'] . "\n\n";
$data .= "Dob: ". $row['dob'] . "\n\n";
$data .= "Height: ". $row['height'] . "\n\n";
$data .= "Add1 : ".$row['address1'] . "\n\n";
$data .= "Add2: ".$row['address2'] . "\n\n";
$data .= "Add3: ".$row['address3'] . "\n\n";
$data .= "Postcode: ".$row['postcode'] . "\n\n";
$data .= "Town: ".$row['town'] . "\n\n";
$data .= "County: ". $row['county']. "\n\n";
$pdf->SetX(140);
$pdf->Ln(2);
$pdf->MultiCell(0, 15, $data);
$from = "me#mydomain.com";
$separator = md5(time());
$eol = PHP_EOL;
// attachment name
$filename = "form.pdf";
// encode data (puts attachment in proper format)
$pdfdoc = $pdf->Output("", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
// send message
if(mail($to, $subject, $body, $headers)){
echo "<b>Email successfully sent</b>";
}
else{
echo "Your message could not be sent.";
}
}
?>
Any help will be highly appreciated.

I actually have some experience with single-handedly writing this kind of thing from scratch. After years of maintaining a home-brewed PHP e-mail builder, my advice is that you shouldn't. It certainly takes less time and resources to research and find the most well-supported, mainstream solution today (whenever today is) than to write your own (and to pay for all the inherent bugs with your time and/or resources).

Related

PHP Code with broken syntax works, when I rewrite it properly it breaks

I'm new to PHP and as a web developer have only been using it to write simple contact forms. Recently I was making a contact form with a file upload feature, not knowing any PHP I found a solution online here. I like it quite a bit because it sends an email from the domain to a personal gmail, which wasn't possible with my old PHP code. I tried to change it up a bit so the $message formatting looks a bit better and so I can use it as a contact form WITHOUT file upload. This is what I got:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['tel'];
$subj = $_POST['subject'];
$usermessage = $_POST['message'];
// $message ="Name = ". $name . "\r\n Email = ". $email . "\r\n Phone = ". $phone . "\r\n Message = ". $usermessage; ------- original $message code with what looks like broken syntax
// new $message code that does not work
$message = "Name: ".$name. "\r\n";
$message .= "Email: ".$email. "\r\n";
$message .= "Phone: ".$phone. "\r\n";
$message .= "Message: ".$usermessage. "\r\n";
$subject = $subj;
$fromname ="Someone";
$fromemail = 'info#domain.com';
$mailto = 'personalemail#gmail.com';
// $content = file_get_contents($fileName);
// $content = chunk_split(base64_encode($content));
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (RFC)
$eol = "\r\n";
// main header (multipart mandatory)
$headers = "From: ".$fromname." <".$fromemail.">" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $message . $eol;
// attachment
// $body .= "--" . $separator . $eol;
// $body .= "Content-Type: application/octet-stream; name=\"" . $filenameee . "\"" . $eol;
// $body .= "Content-Transfer-Encoding: base64" . $eol;
// $body .= "Content-Disposition: attachment" . $eol;
// $body .= $content . $eol;
// $body .= "--" . $separator . "--";
//SEND Mail
if (mail($mailto, $subject, $body, $headers)) {
echo "mail send ... OK"; // do what you want after sending the email
header('Location: success.html');
} else {
echo "mail send ... ERROR!";
print_r( error_get_last() );
}
Basically I just commented out what looked like code for the file, so it wouldn't send a 'noname' attachment with no file extension. That worked, but the formatting had some weird indentations, random text color changes to a a:visited blue/purple, and the = wasn't visually appealing, I'd rather have a ':'. Plus, the syntax looked broken with quotations in the wrong place. So I made the new message code that can be clearly seen, and commented out the original broken one line $message code, and now the email sends with no content. How is this possible? How do I fix this code?
It seems the slightest thing breaks the code to where a message sends completely empty or only one field sends. Commenting a line out, replacing the '=' with ':' in the original $message code, deleting comments, all could possibly break this again.
Change to
// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $eol; // This line added!
$body .= $message . $eol;

PHP function success but mail not recieved [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 1 year ago.
I made a form with PHP to send mail, When I test it locally it runs fine I receive an email with all the information but when I put it live on a host it says SUCCESS but I never receive the mail. Maybe is something wrong with the code because i have an other form without the ATTACH file and it runs perfecrly
$filenameee = $_FILES['file']['name'];
$fileName = $_FILES['file']['tmp_name'];
$name = $_POST['name'];
$email = $_POST['email'];
$title=$_POST['title'];
$prototip=$_POST['prototip'];
$description = $_POST['descripton'];
$message ="Name = ". $name . "\r\n Email = " . $email . "\r\n \r\n Naslov = ".$title . "\r\n Opis = ".$description;
$subject ="My email subject";
$mailto = 'levchegochev#gmail.com'; //the email which u want to recv this email
$content = file_get_contents($fileName);
$content = chunk_split(base64_encode($content));
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (RFC)
$eol = "\r\n";
// main header (multipart mandatory)
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$body .= "Content-Transfer-Encoding: 8bit" . $eol;
$body .= $message . $eol;
// attachment
$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/octet-stream; name=\"" . $filenameee . "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";
//SEND Mail
if (mail($mailto, $subject, $body, $headers)) {
echo "<script>
swal({
title: 'Ви благодариме за вашата апликација!',
text: 'Kе ве контактираме во рок од 24 часа',
icon: 'success',
button: 'Супер!',
});
</script>";
} else {
echo "<script>alert('Mail was not sent. Please try again later');</script>";
}
Updated answer
Set the following parameters in your html form:
<form action="your_target_php_file.php" method="post" enctype="multipart/form-data">
PHP file:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// file data from html element input[type='file']
$file = (object) [
'tmp_name' => $_FILES['file']['tmp_name'],
'name' => $_FILES['file']['name'],
'size' => $_FILES['file']['size'],
'type' => $_FILES['file']['type'],
'error' => $_FILES['file']['error'],
];
// other POST data
$post = (object) [
'name' => $_POST['name'],
'email' => $_POST['email'],
'title' => $_POST['title'],
'prototip' => $_POST['prototip'],
'description' => $_POST['descripton']
];
// email message
$message = "Name = ". $post->name . "\r\n Email = " . $post->email . "\r\n\r\n Naslov = ";
$message .= $post->title . "\r\n Opis = ".$post->description;
// email subject
$subject = "My email subject";
//the email which u want to recv this email
$mailto = 'levchegochev#gmail.com';
//read from the uploaded file
$handle = fopen($file->tmp_name, "r");
$content = fread($handle, $file->size);
fclose($handle);
$encoded = chunk_split(base64_encode($content));
// boundary
$boundary = md5("random");
// email headers
$headers[] = "MIME-Version: 1.0";
$headers[] = "From: " .explode("#", $post->email)[0]. " <{$post->email}>";
$headers[] = "Reply-To: {$mailto}";
$headers[] = "Content-Type: multipart/mixed;";
$headers[] = "boundary = {$boundary}";
//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";
// Attaching the encoded file with email
$body .= $encoded;
if (mail($post->email, $subject, $body, implode("\r\n", $headers)))
echo ("<script>
swal({
title: 'Ви благодариме за вашата апликација!',
text: 'Kе ве контактираме во рок од 24 часа',
icon: 'success',
button: 'Супер!',
});
</script>");
} else {
echo "<script>window.alert('Mail was not sent. Please try again later');</script>";
}
}
I changed your code a bit, I believe it will work for you.

php mail function can not send attached pdf file and message body

I want to send mail through php mail function. For that I googled it and found the code which send mail attached with pdf file. Result is fine, mail send but mail only send attached pdf file it can not send message body.
Here is Code:
<?php
$name = "myname";
$to = "receive#gmail.com";
$email = "sender#gmail.com";
$from = "myname";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$fileatt = $_SERVER['DOCUMENT_ROOT']."/xxx/ticket.pdf";
$fileatttype = "application/pdf";
$fileattname = "ticket.pdf";
$headers = "From: $from";
// File
$file = fopen($fileatt, 'rb');
$data = fread($file, filesize($fileatt));
fclose($file);
// This attaches the 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}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"-{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$mainMessage . "\n\n";
$data = chunk_split(base64_encode($data));
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"-{$mime_boundary}-\n";
// Send the email
if(mail($to, $subject, $message, $headers)) {
echo "The email was sent.";
}
else {
echo "There was an error sending the mail.";
}
?>
I can not identify where i done mistake, please help me and give some suggestion.
Note: Don't Give suggestion to use PHPMailer.
Thanks
You can try this code:
$to = "youremail#gmail.com";
$from = "Myname <sender#gmail.com>";
$subject = "Test Attachment Email";
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// attachment name
$filename = "document.pdf";
//$pdfdoc is PDF generated by FPDF
$pdfdoc = "/opt/transmail/2018-03-07_32_11564_invoice.pdf";
$attachment = chunk_split(base64_encode($pdfdoc));
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$message = "Thanks";
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
// send message
if (mail($to, $subject, $body, $headers)) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR";
}
hope this will work for you.

HTML/PHP mail() : Content Not Showing in Email with Attachment sent Through PHP

The issue: Emails sent with HTML and attachment do not show content. There is no issue with the attachment. Before I attempted to send it as an HTML email, the message and attachment were fine.
The code: I am using the following code to send emails with attachments:
//Email to Customer or Tech
$file = "../PDF/phptopdf/".$_GET['pdf'];
$lgth = strlen($_GET['pdf']);
$intsta = strpos($_GET['pdf'],'/')+1;
$intend = $lgth - strpos($_GET['pdf'],'.');
$intendname = $lgth - strpos($_GET['pdf'],'_');
$filename = substr($_GET['pdf'],$intsta,-$intend);
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (RFC)
$eol = "\r\n";
// main header (multipart mandatory)
$headers = "From: ".$_SESSION['userFName']." ".$_SESSION['userLName']." <".$_SESSION['email'].">" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 8bit" . $eol;
// message
$body = "--" . $separator . $eol;
$body .= "Content-Type: text/html; charset=iso-8859-1" . $eol;
$body .= "Content-Transfer-Encoding: quoted-printable" . $eol;
if ($_POST['sendToTech'] == '1') {
$mailto = $_POST['techEmail'];
$subject = 'New Work Order for '.$compName;
$pos = strpos($_POST['techName'],' ');
$techFName = substr($_POST['techName'],0,$pos);
$message = "<html><body>";
$message .= "<table style='border:1px solid #000;font-size:18px;line-height:20px;'><tr><td style='text-align:center;padding:10px;'><img src='MY LOGO URL' /></tr></td>";
$message .= "<tr><td style='padding:10px;'>";
$message .= "Hello ".$techFName.", <br/><br/>";
$message .= "I have assigned work order #00-".$_GET['idQ']." for ".$compName." to you. <br/>";
$message .= "The work is scheduled for ".date('F jS, Y \a\t g:i A',strtotime($serviceDate))." at ".$address.". <br/>";
$message .= "Click on the attachment to view the work order or <a href='MYURL".$_GET['pdf']."'>Click Here</a>. <br/><br/>";
$message .= "Thank you, <br/>";
$message .= $_SESSION['userFName']."<br/><br/></tr></td></table></body></html>";
$body .= $message . $eol;
// attachment
$body .= "--" . $separator . $eol;
$body .= "Content-Type: application/pdf; name=\"" . $filename . "\"" . $eol;
$body .= "Content-Transfer-Encoding: base64" . $eol;
$body .= "Content-Disposition: attachment" . $eol;
$body .= $content . $eol;
$body .= "--" . $separator . "--";
//SEND Mail
if (mail($mailto, $subject, $body, $headers)) {
echo "<span class='message mg'>Work Order #00-".$idQ." has been emailed to ".$_POST['techName']." at ".$_POST['techEmail']."</span><br/>";
} else {
$msg[] = "Error: " . $mysqli->error;
echo "<span class='message alert'>An error occured while attempting to send Work Order #00-".$idQ." to ".$_POST['techEmail']."</span>";
}
}
When the email arrives it looks like this:
Email in Gmail
But, when I look into the original message I see the content that is not displayed:
Original Message View
Solutions that I have attempted:
Removing "This is a multi-part message in MIME format" (PHP mail function html content not visible in email)
Changing $body .= "Content-Type: text/html; charset=iso-8859-1" . $eol; -- to text/plain (just to see if that would do anything...)
Changing $headers .= "Content-Transfer-Encoding: 8bit" . $eol; -- from 7bit and quoted-printable
Removing <html><body> and closing tags

php mail() : attachments sent but not body text

I have seen similar questions, but nothing directly on topic...
I have a multi part mail script with attachments. The attachments get sent fine, but the main body text, which is populated from a form, isn't sent. I tried sending with the attachment function commented out and the form elements went through. My code is:
if (empty($_POST['RadioGroup1'])){
echo "PLease select a version of message";
} else {$selected_msg = $_POST['RadioGroup1'];}
if (isset($_FILES) && (bool) $_FILES){
$files = array();
// Check for attachments
$questions = $_POST['questions'];
//loop through all the files
foreach($_FILES as $name=>$file){
// define the variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
//check if file type allowed
$path_parts = pathinfo($file_name);
//move this file to server
$server_file = "reports/$path_parts[basename]";
move_uploaded_file($temp_name, $server_file);
//add file to array of file
array_push($files,$server_file);
}
// define mail var
$to = $email;
$from = "[server]";
$subject = "Closed Case: $case_id $casename";
$headers = "From: $from";
//define boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Header know about boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// Define plain text mail
$message .= "--{$mime_boundary}\n";
$message .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n" . $message . "\r\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
foreach($files as $file){
$aFile = fopen($file, "rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"}\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
} // END foreach attachment
$message .= $questions;
$message .= $selected_msg;
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p class=\"success\">mail sent to $to!</p>";
The script runs without errors and does sent the file attachments OR the body text. Any insight would be appreciated.
Instead of calling the form variables from within --- $message .= $questions;. $message .= $selected_msg; Hard code the variables into the $message.=
Like-- $message .= "Content-Transfer-Encoding: 7bit\r\n" . $questions . "\r\n" . $selected_msg . "\r\n";
If you like add both text and attachment in email, then used bellow code
$bodyMeaasge = 'Your Body Meaasge';
$filename = yourfile.pdf;
$path = '../';
$mpdf->Output($path.$filename,'F');
$file = $path . "/" . $filename;
$to = "senderemail#gmail.com";
$subject = "My Subject";
$random_hash = md5(date('r', time()));
$headers = "From:your#domain.com\r\n" .
"X-Mailer: PHP" . phpversion() . "\r\n" .
"MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $random_hash\r\n\r\n";
if(file_exists($file))
{
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
//plain text
$body = "--$random_hash\r\n";
$body .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($bodyMeaasge));
//attachment
$body .= "--$random_hash\r\n";
$body .="Content-Type: application/octet-stream; name=".$filename."\r\n";
$body .="Content-Disposition: attachment; filename=".$filename."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $content;
}else{
//plain text
$body = "--$random_hash\r\n";
$body .= "Content-Type: text/html; charset=utf-8\r\n"; // use different content types here
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($bodyMeaasge));
}
if (mail($to,$subject,$body,$headers)) {
header("Location:".$url.'&success=successfully mail send.');
} else {
header("Location:".$url.'&error=There was a problem sending the email.');
}

Categories