I've tried searching the forums, I have found that some other people have been having the same issue as me, but haven't found a solution that works yet.
I am creating a portal where the customer enters their information in the form and uploads an image, which is then sent as an attachment to the email.
I am finding that when I use the PHP mail() function, it is sending duplicate emails, one with the POST data, and one without. I am only calling the function once, and as far as I can tell I am only loading the page once.
Here is my code:
//recipient address (made up but you get the idea)
$to = 'sales#skycommunications.net';
//subject of email
$subject = 'Phone Order from Online Portal';
//create body of message
$message = "An order has been placed using the Portal.\n";
$message .= "The order details are as follows:\n";
$message .= "\n";
$message .= "First Name: ".$_POST["firstname"]."\n";
$message .= "Last Name: ".$_POST["lastname"]."\n";
$message .= "Phone Number: ".$_POST["phonenumber"]."\n";
$message .= "Email Address: ".$_POST["emailaddress"]."\n";
$message .= "\n";
$message .= "Phone: " . $_POST["phone"] . "\n";
$message .= "Color: " . $_POST["color"] . "\n";
$message .= "Voice Plan: " . $_POST["voiceplan"] . "\n";
$message .= "Data Plan: " . $_POST["dataplan"] . "\n";
//get file details from previous form
$file_tmp_name = $_FILES['uploaded_file']['tmp_name'];
$file_name = $_FILES['uploaded_file']['name'];
$file_size = $_FILES['uploaded_file']['size'];
$file_type = $_FILES['uploaded_file']['type'];
//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));
//random number for headers
$boundary = md5("sanwebe");
//create the headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: noreply#skycommunications.net\r\n";
$headers .= "Reply-To: noreply#skycommunications.net\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text info
$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 info
$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;
//send the email
mail($to, $subject, $body, $headers);
Everything works beautifully except for the fact that it sends one email complete with the information and attachment, another with no information from POST and a 0kb attachment. Any ideas? Is it a problem with the server possibly?
Wrap all of the mail code some sort of validation logic. Overall you want to:
Ensure that the request being made is in fact a POST request
Ensure that the required POST parameters are included in the request.
You can achieve that with code similar to the following:
function validRequest() {
return (
// make sure that the request type is POST
$_SERVER['REQUEST_METHOD'] === 'POST'
// make sure the required POST variables were included
&& isset($_POST['firstname'])
&& isset($_POST['lastname'])
&& isset($_POST['phonenumber'])
&& isset($_POST['emailaddress'])
&& isset($_POST['phone'])
&& isset($_POST['color'])
&& isset($_POST['voiceplan'])
&& isset($_POST['dataplan'])
// make sure that there is a file
&& $_FILES['uploaded_file']
);
}
if (validRequest()) {
// your email code
} else {
// there was some sort of error
}
I would bet if you looked at your server log you would be getting some errors saying that the array key does not exist.
My bet is that you are redirecting with .htaccess or some other redirect. It would be called once with the post data and called once more after the redirect.
A simple fix would be to prepend:
if(!empty($_POST['someinput'])) {
//send email
}
if you put this code on top of the page as it's then on initial page load it'll send a blank email to sales#skycommunications.net.
Second email will be sent when you actually submit the form.
To prevent this you need to wrap this in a IF condition and check $_POST is not empty. this way script won't execute on initial page load.
Best way is checking the submit value and you can also validate other post values as well.
Assume your submit button name is "submit".
if (isset($_POST['submit']) && !empty($_POST['submit'])){
//recipient address (made up but you get the idea)
$to = 'sales#skycommunications.net';
//subject of email
$subject = 'Phone Order from Online Portal';
//create body of message
$message = "An order has been placed using the Portal.\n";
$message .= "The order details are as follows:\n";
$message .= "\n";
$message .= "First Name: ".$_POST["firstname"]."\n";
$message .= "Last Name: ".$_POST["lastname"]."\n";
$message .= "Phone Number: ".$_POST["phonenumber"]."\n";
$message .= "Email Address: ".$_POST["emailaddress"]."\n";
$message .= "\n";
$message .= "Phone: " . $_POST["phone"] . "\n";
$message .= "Color: " . $_POST["color"] . "\n";
$message .= "Voice Plan: " . $_POST["voiceplan"] . "\n";
$message .= "Data Plan: " . $_POST["dataplan"] . "\n";
//get file details from previous form
$file_tmp_name = $_FILES['uploaded_file']['tmp_name'];
$file_name = $_FILES['uploaded_file']['name'];
$file_size = $_FILES['uploaded_file']['size'];
$file_type = $_FILES['uploaded_file']['type'];
//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));
//random number for headers
$boundary = md5("sanwebe");
//create the headers
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: noreply#skycommunications.net\r\n";
$headers .= "Reply-To: noreply#skycommunications.net\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text info
$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 info
$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;
//send the email
mail($to, $subject, $body, $headers);
}
Eureka! Thanks for the help everyone!
Here is the code I used to validate the POST data prior to calling the mail() function:
//check for empty post so duplicate emails are not sent
if (
isset($_POST["firstname"]) &&
isset($_POST["lastname"]) &&
isset($_POST["phonenumber"]) &&
isset($_POST["emailaddress"]) &&
isset($_POST['phone']) &&
isset($_POST['color']) &&
isset($_POST['voiceplan']) &&
isset($_POST['dataplan']) &&
isset($_FILES["uploaded_file"])
)
{
mail($to, $subject, $body, $headers);
}
I found if I used an else statement, that the page wouldn't finish loading, so I just used the if statement, and presto, only one email with the POST data is being sent.
Thanks again for the help everyone.
Related
The s_name and s_email fields don't show up in the email sent, only the attachments and message show up. Please assist with any changes to the code to show all form fields in the email.
I have looked at a number of posts but can't seem to find the answer to the problem and assistance will be appreciated.
<?php
if($_POST && isset($_FILES['file'])) {
$recepient_email = "recepient#yourmail.com"; //recepient
$from_email = "info#your_domain.com"; //from email using site domain.
$subject = "Attachment email from your website!"; //email subject line
$sender_name = filter_var($_POST["s_name"], FILTER_SANITIZE_STRING);
//capture sender name
$sender_email = filter_var($_POST["s_email"], FILTER_SANITIZE_STRING); //capture sender email
$sender_message = filter_var($_POST["s_message"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['file'];
//php validation
if(strlen($sender_name)<4){
die('Name is too short or empty');
}
if (!filter_var($sender_email, FILTER_VALIDATE_EMAIL)) {
die('Invalid email');
}
if(strlen($sender_message)<4){
die('Too short message! Please enter something');
}
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("sanwebe.com");
if($file_count > 0){ //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message 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($sender_message));
//attachments
for ($x = 0; $x < $file_count; $x++) {
if(!empty($attachments['name'][$x])) {
if($attachments['error'][$x]>0) { //exit script and output error if we encounter any
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);
die($mymsg[$attachments['error'][$x]]);
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$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;
}
}
} else { //send plain email otherwise
$headers = "From:".$from_email."\r\n".
"Reply-To: ".$sender_email. "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $sender_message;
}
$sentMail = #mail($recepient_email, $subject, $body, $headers);
if($sentMail) { //output success or failure messages
die('Thank you for your email');
} else {
die('Could not send mail! Please check your PHP mail configuration.');
}
}
?>
Are you able to see all your form fields doing this?
<?php print_r($_POST); ?>
Double-check if all your form fields has the name attr and if their are matching to fields printed above.
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
You have an extra double quote? Should be like this:
$headers .= "Reply-To:" .$sender_email. "\r\n";
Your $sender_name is not used in the email, only when you check if the length is < 4.
PHP contact form is sending encoded text on email body. The email contains
an attachment and some text from input fields. The message must be decoded before its sent. How can I decode the "$message" with right text that is inputted?
Please have a look at the code given below:
if (isset($_POST['submit'])) {
if ($_POST['email'] == '' || $_FILES['file_upload'] == '' || $_POST["fname"] == '' || $_POST["lname"] == '' || $_POST["message"] == '') {
echo '<p class="red-info">Please Fill All The Fields</p>';
} else {
$from_email = $_POST['email']; //from mail, it is mandatory with some hosts
$recipient_email = 'myemail#gmail.com'; //recipient email (most cases it is your personal email)
//Capture POST data from HTML form and Sanitize them,
$sender_fname = filter_var($_POST["fname"], FILTER_SANITIZE_STRING); //sender name
$sender_lname = filter_var($_POST["fname"], FILTER_SANITIZE_STRING); //sender name
$sender_phone_1 = filter_var($_POST["phone_1"], FILTER_SANITIZE_STRING); //sender name
$sender_phone_2 = filter_var($_POST["phone_2"], FILTER_SANITIZE_STRING); //sender name
$sender_phone_3 = filter_var($_POST["phone_3"], FILTER_SANITIZE_STRING); //sender name
$sender_phone = $sender_phone_1 . ' ' . $sender_phone_2 . ' ' . $sender_phone_3; //sender name
$reply_to_email = filter_var($_POST["email"], FILTER_SANITIZE_STRING); //sender email used in "reply-to" header
$subject = 'Contact Form'; //get subject from HTML form
$message = filter_var($_POST["message"], FILTER_SANITIZE_STRING); //message
/* //don't forget to validate empty fields
if(strlen($sender_name)<1){
die('Name is too short or empty!');
}
*/
//Get uploaded file data
$file_tmp_name = $_FILES['file_upload']['tmp_name'];
$file_name = $_FILES['file_upload']['name'];
$file_size = $_FILES['file_upload']['size'];
$file_type = $_FILES['file_upload']['type'];
$file_error = $_FILES['file_upload']['error'];
if ($file_error > 0) {
die('Upload error or No files uploaded');
}
//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("sanwebe");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:" . $from_email . "\r\n";
$headers .= "Reply-To: " . $reply_to_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 .= "<br />First Name:" . $sender_fname;
$body .= "<br />Last Name:" . $sender_lname;
$body .= "<br />Phone:" . $sender_phone;
$body .= "<br />Message:";
$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 (isset($sentMail)) //output success or failure messages
{
echo '<p class="green-info">Your Email Has Been Submitted!We will contact soon.</p>';
echo "<script>document.contact.reset();</script>";
header("location: contect.php");
} else {
die('Could not send mail! Please check your PHP mail configuration.');
}
}
}
Have you tried setting the content type ?
$headers .= "Content-Type: text/html;";
Changed to this and that worked thanks :)
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:" . $from_email . "\r\n";
$headers .= "Reply-To: " . $reply_to_email . "" . "\r\n";
$headers .= "Content-Type: multipart/alternative; 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 .= "\n First Name:" . $sender_fname;
$body .= "\n Last Name:" . $sender_lname;
$body .= "\n Phone:" . $sender_phone;
$body .= "\n Message:" .$message;
$body .= chunk_split(base64_encode());
I have a html form where i ask my users to fill in their personal and career details and attach their resume. I would like to get those details (form data and the attachment) sent to an email using php.... Any help will be much appreciated....
here is my code for sending mail... Using this i get the file attachment but not the other form data... Pls help where i am going wrong...
<?php
// Settings - working good
$name = "Name goes here";
$email = "test#gmail.com";
$to = "$name <$email>";
$from = "Vijay";
$subject = "Here is your attachment";
$mainMessage = "Hi, here's the file.";
$attachments = $_FILES['attachment'];
if(empty($_POST['title']) ||
empty($_POST['exp']) ||
empty($_POST['skill']) ||
empty($_POST['qual']) ||
empty($_POST['certf']) ||
empty($_POST['domain']) ||
empty($_POST['fname']) ||
empty($_POST['lname']) ||
empty($_POST['phone']) ||
empty($_POST['email']) ||
empty($_POST['csal']) ||
empty($_POST['job']) ||
// empty($_POST['file']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}$title = strip_tags(htmlspecialchars($_POST['title']));
$exp = strip_tags(htmlspecialchars($_POST['exp']));
$skill = strip_tags(htmlspecialchars($_POST['skill']));
$qual = strip_tags(htmlspecialchars($_POST['qual']));
$certf = strip_tags(htmlspecialchars($_POST['certf']));
$domain = strip_tags(htmlspecialchars($_POST['domain']));
$fname = strip_tags(htmlspecialchars($_POST['fname']));
$lname = strip_tags(htmlspecialchars($_POST['lname']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$csal = strip_tags(htmlspecialchars($_POST['csal']));
$job = strip_tags(htmlspecialchars($_POST['job']));
// File
//Get uploaded file data
$file_tmp_name = $_FILES['attachment']['tmp_name'];
$file_name = $_FILES['attachment']['name'];
$file_size = $_FILES['attachment']['size'];
$file_type = $_FILES['attachment']['type'];
$file_error = $_FILES['attachment']['error'];
if($file_error > 0)
{
die('Upload error or No files uploaded');
}
//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("sanwebe");
//header
$headers = "MIME-Version: 1.0\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;
$Message = "You have received a new resume from your website career application form.\n\n"."Here are the details:\n\n
Title: ".$title."\n
Experience: ".$exp."\n
Skill: ".$skill."\n
Qualification: ".$qual."\n
Domain: ".$domain."\n
First Name: ".$fname."\n
Last Name: ".$lname."\n
Phone: ".$phone."\n
Email: ".$email_address."\n\n
Current Salary: ".$csal."\n\n
Job: ".$job."\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.";
echo "$fileattname";
}
else {
echo "There was an error sending the mail.";
}
?>
You want to use proven, well tested libraries like Swiftmailer or Zend\Mail instead of writing the code like you do.
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.');
}
I have a really nice looking HTML Template that I now need to implement into my mailing system. I am currently using this to send emails:
$to = $dbuser;
$subject = "Welcome";
$from = "support#mysite.com";
$headers = "From: $from";
$server = "";
ini_set ("SMTP", $localhost);
$url="";
$msg="$url";
$body = Example Text!
mail($to, $subject, $body, $headers);
How would I include a HTML template (along side CSS) directly into the $body variable of my php email form?
I've done quite a bit of research but I can't find anything substantial.
Your missing the header required for the email client to interpret the message as HTML. Add the following to your headers:
$headers = "From: " . $from . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
One way of doing this that I have used in the past is to create the page as you would normally (using html/php etc) and then use file_get_contents($url) like so:
$body = file_get_contents("http://mydomain.com/emailtemplates/template.php?name=John Doe&subject=Hello");
Because you are using http:// the php is executed rather than pulled into the template, simple but effective!
I also would advise you to use inline css and don't be afraid to use tables!
http://php.net/manual/en/function.mail.php - example #5
also remember that in HTML emails you're strongly advised to use inline CSS and old-school HTML formatting where possible to assure maximum compatibility with different email clients. Also no divs - just plain old good table-s
First of all you need to add some headers, in order for the HTML to display correctly.
Taken from the mail() PHP documentation, this is how you do it:
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
After that, I'm assuming $body is where the text should be, so it's a matter of putting all the HTML between quotation marks (escaping every quotation mark in your HTML with a backwards slash), and that's pretty much it.
I wrote this for myself yesterday:
Create your html and put it in a file named "./email.html" Copy and
paste the code below to a php file in the same dir as the html file.
Modify the image names if you use them in the HTML just do so like so: src="cid:world.jpg"
And thats it...I think. =)
//attachment file paths/names
$files[0] = './world.jpg';
$files[1] = './world2.jpg';
$to = '';
$bcc = "";
$subject = '';
$from = "";
$htmlx = '';
$handle = #fopen("./email.html", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$htmlx .= $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x".$semi_rand."x";
$headers = "From: $from \n";
$headers .= "Reply-To: $from \n";
$headers .= 'Bcc: '. $bcc . "\n";
$headers .= "MIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . ' boundary="'.$mime_boundary.'"'."\n";
$headers .= "X-Author: <Timothy Martens>\n";
$message = '--'.$mime_boundary."\n";
$message .= 'Content-Type: text/html; charset=UTF-8'."\n";
$message .= "Content-Transfer-Encoding: 7bit\n\n\n". $htmlx . "\n\n\n";
// preparing attachments
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--".$mime_boundary."\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-ID: <".basename($files[$i]).">\n".
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
$message .= "--".$mime_boundary."--";
if (mail($to, $subject, $message, $headers)) {
echo 'Your message has been sent.'."\n";
} else {
echo 'There was a problem sending the email.'."\n";
}