I have a form to signup yourself in a mailing list.
I had set up the script to send me a mail for every signup and confirmation.
The last days I saw a bunch of empty submissions (rejected). Turns out filter_input is that good :-)
But I want to see the input of the malicious users, so I'm encoding the input and sending it to me by mail
htmlentities($_POST['userName'], ENT_QUOTES, "UTF-8")
Is that secure?
Should I add mysql_real_escape_string() ?
It is possible to craft a post in such a way that will be able to do any harm while sending the mail to me?
I'm not writing rejected submisions to the database, only mailing them to me.
Here's the relevant code.
<?php
$userName = filter_input(INPUT_POST, 'userName', FILTER_SANITIZE_STRING);
$userEmail = filter_input(INPUT_POST, 'userEmail', FILTER_VALIDATE_EMAIL);
if(!checkdnsrr(array_pop(explode("#",$userEmail)),"A"))
$hostInvalido = true;
if(!empty($userName) && $userName!==FALSE && !empty($userEmail) && $userEmail!==FALSE && !isset($hostInvalido) ) {
//All ok
} else {
echo "Datos invalidos, por favor, intenta nuevamente.";
$fromaddress="info#example.com";
$fromname="Error reporting";
$to= "webmaster <webmaster#example.com>";
$subject="MailList: Error ";
$userName = htmlentities($_POST['userName'], ENT_QUOTES, "UTF-8"); // is this secure?
$userEmail = htmlentities($_POST['userEmail'], ENT_QUOTES, "UTF-8");
$body = "Nombre: $userName<br>Email: $userEmail";
$body .= (isset($hostInvalido)) ? "<br>Host invalido" : "";
$ret = send_mail($to, $body, $subject, $fromaddress, $fromname, $attachments=false);
}
// I'm including this function so you can analyze it for any possible vulnerability
function send_mail($to, $body, $subject, $fromaddress, $fromname, $attachments=false) {
$eol="\r\n";
$mime_boundary=md5(time());
# Common Headers
$headers = "";
$headers .= "From: ".$fromname."<".$fromaddress.">".$eol;
$headers .= "Reply-To: ".$fromname."<".$fromaddress.">".$eol;
$headers .= "Return-Path: ".$fromname."<".$fromaddress.">".$eol; // these two to set reply address
$headers .= "Message-ID: <".time()."-".$fromaddress.">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol; // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;
# Open the first part of the mail
$msg = "--".$mime_boundary.$eol;
$htmlalt_mime_boundary = $mime_boundary."_htmlalt"; //we must define a different MIME boundary for this section
# Setup for text OR html -
$msg .= "Content-Type: multipart/alternative; boundary=\"".$htmlalt_mime_boundary."\"".$eol.$eol;
# Text Version
$msg .= "--".$htmlalt_mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=UTF-8".$eol; //iso-8859-1
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg .= strip_tags(str_replace("<br>", "\n", $body)).$eol.$eol; //mb_substr($body, (strpos($body, "<body>")+6))
# HTML Version
$msg .= "--".$htmlalt_mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=UTF-8".$eol;//iso-8859-1
$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$msg .= $body.$eol.$eol;
//close the html/plain text alternate portion
$msg .= "--".$htmlalt_mime_boundary."--".$eol.$eol;
if ($attachments !== false)
{
for($i=0; $i < count($attachments); $i++)
{
if (is_file($attachments[$i]["file"]))
{
# File for Attachment
$file_name = mb_substr($attachments[$i]["file"], (strrpos($attachments[$i]["file"], "/")+1));
$handle=fopen($attachments[$i]["file"], 'rb');
$f_contents=fread($handle, filesize($attachments[$i]["file"]));
$f_contents=chunk_split(base64_encode($f_contents)); //Encode The Data For Transition using base64_encode();
$f_type=filetype($attachments[$i]["file"]);
fclose($handle);
# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: ".$attachments[$i]["content_type"]."; name=\"".$file_name."\"".$eol; // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Description: ".$file_name.$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$file_name."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
}
}
}
# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol; // finish with two eol's for better security. see Injection.
# SEND THE EMAIL
ini_set('sendmail_from',$fromaddress); // the INI lines are to force the From Address to be used !
$mail_sent = mail($to, $subject, $msg, $headers);
ini_restore('sendmail_from');
return $mail_sent;
}
?>
XSS injections is mainly javascript, so using htmlentities() is sufficient :)
If you are still worried, drop the message into a < textarea>< /textarea> and then mail it.
Related
Trying to build a code to send password reset link through email in response to those who request it.
The email is received on hotmail and gmail, but not on particular mail client I do not know the configuration.
Of course, I tried several arrangements regarding the quotes and doubles-quotes, but it did not give anything.
<?php
$site = "http://www.example.fr";
$from = "info#example.fr";
$nom = "DLSS";
$limite = "_----------=_parties_".md5(uniqid (rand()));
$sujet = "Password Reset";
$text = "Please click on this link to initialize your password.";
$html = "Please click on this link to initialize your password.";
$from = $nom." <".$from.">";
$header = "From: ".$from."\n";
$header .= "Reply-to: ".$from."\n";
$header .= "Return-Path: ".$from."\n";
$header .= "Organization: ".$nom."\n";
$header .= "X-Sender: <".$site.">\n";
$header .= "X-Mailer: PHP/".phpversion()."\n";
$header .= "X-auth-smtp-user: ".$from." \n";
$header .= "X-abuse-contact: ".$from." \n";
$header .= "Date: ".date("D, j M Y G:i:s O")."\n";
$header .= "MIME-Version: 1.0\n";
$header .= "Content-Type: multipart/alternative; boundary=\"".$limite."\"";
$message = "";
$message .= "--".$limite."\n";
$message .= "Content-Type: text/plain\n";
$message .= "charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: 8bit\n\n";
$message .= $text;
$message .= "\n\n--".$limite."\n";
$message .= "Content-Type: text/html; ";
$message .= "charset=\"iso-8859-1\"; ";
$message .= "Content-Transfer-Encoding: 8bit;\n\n";
$message .= $html;
$message .= "\n--".$limite."--";
mail($eml, $sujet, $message, $header);
?>
In summary, the email is received by this particular mail client when I replace these two lines there :
$text = "Please click on this link to initialize your password.";
$html = "Please click on this link to initialize your password.";
With these two lines here :
$text = "Test Email with link. link";
$html = "Test Email with link. link";
Or with these two lines here :
$text = $eml . " - " . $cod;
$html = $eml . " - " . $cod;
Finally, the problem is in the combination of these two parts that are the web address and the two variables, it's been three days that I try to solve this problem but I can not do it alone, it would be really nice to have help, Thanks in advance !
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I am using this code for my contact form in a html website but mail is not coming in Gmail Inbox.
Can any one help me i am trying to solve this issue but i don't have any guide.
<?php
session_cache_limiter( 'nocache' );
$subject = $_REQUEST['subject']; // Subject of your email
$to = "iamuser#gmail.com"; //Recipient's E-mail
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "From: " . $_REQUEST['name'].'<'.$_REQUEST['email'] .'>'. "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = 'Name: ' . $_REQUEST['name'] . "<br>";
$message .= 'Company: ' . $_REQUEST['company'] . "<br>";
$message .= $_REQUEST['message'];
if (#mail($to, $subject, $message, $headers))
{
// Transfer the value 'sent' to ajax function for showing success message.
echo 'sent';
// header('Location: ../index.html');
}
else
{
// Transfer the value 'failed' to ajax function for showing error message.
echo 'failed';
}
?>
There are some problem in setting the header.
And most important is that you need to define the correct and valid Email Id in the From section because google generally used to validate the domain, the mail coming from.
If it is not white-listed at google end then it wills end the mail to Spam automatically, that is happening now as I think.
The problem is simple that the PHP-Mail function is not using a well configured SMTP Server.
Nowadays Email-Clients and Servers perform massive checks on the emails sending server, like Reverse-DNS-Lookups, Graylisting and whatevs. All this tests will fail with the php mail() function. If you are using a dynamic ip, its even worse.Use the PHPMailer-Class and configure it to use smtp-auth along with a well configured, dedicated SMTP Server (either a local one, or a remote one) and your problems are
You can try the below code.
$headers = "From: myplace#example.com\r\n";
$headers .= "Reply-To: myplace2#example.com\r\n";
$headers .= "Return-Path: myplace#example.com\r\n";
$headers .= "CC: sombodyelse#example.com\r\n";
$headers .= "BCC: hidden#example.com\r\n";
Reference Link.
https://github.com/PHPMailer/PHPMailerPHPMailer/PHPMailerPHPMailer
There is another code you can try:
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$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()));
$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."--";
if (mail($mailto, $subject, "", $header)) {echo "mail send ... OK";
// or use booleans here} else {echo "mail send ... ERROR!";
}
}
If you are developing this program in local server. The emails will not be sent to your gmail account.
If you want to test your code on a local machine please install Test Mail Server Tool.
No email will be delivered while running on local machine but you will get an idea how the email will look like.
When you run the same on web hosting server, the email will be delivered to the email id specified in $to field.
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.
Just to be clear - I didn't write this code, this is from a previous developer.
Anyway, my client isn't receiving images when uploaded via their form, just a red box with an error message.
As per request here is the whole code:
<?php
function sendMail() {
if (!isset ($_POST['to_email'])) { //Oops, forgot your email addy!
die ("<p>Oops! You forgot to fill out the email address! Click on the back arrow to go back</p>");
}
else {
$to_name = stripslashes($_POST['to_name']);
$from_name = stripslashes($_POST['from_name']);
$from_telephone = stripslashes($_POST['from_telephone']);
$subject = stripslashes($_POST['subject']);
$body = stripslashes($_POST['body']);
$address = stripslashes($_POST['address']);
$to_email = $_POST['to_email'];
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
if (is_uploaded_file($attachment)) { //Do we have a file uploaded?
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose($fp);
}
//Let's start our headers
$headers = "From: $from_name<" . $_POST['from_email'] . ">\n";
$headers .= "Reply-To: <" . $_POST['from_email'] . ">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n";
$headers .= "X-Sender: $from_name<" . $_POST['from_email'] . ">\n";
$headers .= "X-Mailer: PHP4\n";
$headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . $_POST['from_email'] . ">\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";
$message = "------=MIME_BOUNDRY_message_parts\n";
$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .= "Content-Transfer-Encoding: quoted-printable\n";
$message .= "\n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$message .= "Return call on: $from_telephone\n\n";
$message .= "$address\n\n";
$message .= "$body\n";
$message .= "\n";
$message .= "------=MIME_BOUNDRY_message_parts--\n";
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message\n";
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n";
$message .= "Content-Transfer-Encoding: base64\n";
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
$message .= $data; //The base64 encoded message
$message .= "\n";
$message .= "------=MIME_BOUNDRY_main_message--\n";
// send the message
mail("$to_name<$to_email>", $subject, $message, $headers);
print "<p align=\"center\">Thank you for your email.</p>";
}
}
switch ($action) {
case "send":
showForm();
sendMail();
break;
default:
showForm();
}
?>
I'm completely confused by this code as I didn't write it and can't decrypt why "$attachment" and "$attachment_name" are separate strings, if I change the "attachment_name" to "attachment" will my problems be fixed?
The code that you have seems to work for me, but there are a few potential problems. I think perhaps the most important one is that the image is sent using an incorrect Content-Type:, but there are also some other issues detailed below.
Image type
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n";
The application/octet-stream is used as a last resort for sending arbitrary binary data when there is no appropriate content type, or the content type is unknown. You should use a proper image type:
$message .= "Content-Type: " . $_FILES['attachement']['type']
. ";\n\tname=\"" . $attachment_name . "\"\n";
If you want to prevent users from mailing arbitrary files, you can use a white-list:
if (is_uploaded_file($attachment) &&
in_array ($attachment_type, array ('image/gif', 'image/png', 'image/jpg', 'image/jpeg'))) {
$fp = fopen($attachment, "rb"); //Open it
$data = fread($fp, filesize($attachment)); //Read it
$data = chunk_split(base64_encode($data)); //Chunk it up and encode it as base64 so it can emailed
fclose ($fp);
} else {
echo "<p>Useful error message\n";
exit;
}
MIME syntax
$headers .= "X-Priority: 3\n"; //1 = Urgent, 3 = Normal
$headers .= "Return-Path: <" . $_POST['from_email'] . ">\n";
$headers .= "This is a multi-part message in MIME format.\n";
The Return-Path: is the last of your headers. The next line is part of the message body. You need a blank line to separate the message body from the headers. Eg:
$headers .= "Return-Path: <" . $_POST['from_email'] . ">\n";
$headers .= "\n";
$headers .= "This is a multi-part message in MIME format.\n";
Personally, I would add the message body to $message instead. The mail() function doesn't care, it just concatenates the headers and message with a line break. See more about line endings below.
$headers .= "------=MIME_BOUNDRY_main_message \n";
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n";
$message = "------=MIME_BOUNDRY_message_parts\n";
Note that if you do move some of the lines above to $message, you need to insert an extra line break after the Content-Type: header.
$attachment = $_FILES['attachment']['tmp_name'];
$attachment_name = $_FILES['attachment']['name'];
...
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n";
$attachment_name is sent by the browser and is typically the original name of the file uploaded by the user. $attachment is the name of the temporary file where the image is stored on the server. The two are entirely different and are not interchangeable.
You may want to strip control characters (such as line breaks) and double quotes from these variables to prevent malicious users from disrupting the syntax of the headers.
Line endings
According to the Mail syntax, lines should be terminated with a CRLF("\r\n") sequence, but it is not clear which line ending should be used when calling the mail() function. The PHP documentation says:
If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.
$_POST[] data
You should not use raw data from $_POST[] in your mail headers. A malicious user could easily insert their own headers (such as Bcc:) to send spam to arbitrary addresses. You should at least filter out control characters (such as line breaks) and perhaps also filter or escape angle brackets and double quotes depending on usage.
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";
}