This question already has an answer here:
HTML in php mail function
(1 answer)
Closed 8 years ago.
I have read a couple of posts on here about this already, so I know that I need to use the file_get_contents function to do this, but I have a bit more advanced need. I need to be able to call in data submitted by a user as well as call in the needed HTML to make the email look nicer. Here is some of my code:
First off, know the structure I have, inside index.php is my html form, and action="complete.php".
At the top of complete.php, I have this:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$evaluator_email = $_POST["evaluator_email"];
$teacher_email = $_POST["teacher_email"];
$evaluator = $_POST["evaluator"];
$teacher = $_POST["teacher"];
$date = $_POST["date"];
$teacher_body = "Hello " . $teacher . ", recently, " . $evaluator . " created a teacher evaluation for your session on " . $date . ". ";
$evaluator_body = "Hello " . $evaluator . ", your evaluation of " . $teacher . " was successfully sent to " . $teacher_email . ". ";
mail($teacher_email , "Evaluation" , $teacher_body , "From: $evaluator");
mail($evaluator_email , "Evaluation" , $evaluator_body , "From: Teacher Evaluation Tool");
}
?>
Which all works fine, but now I want to be able to include HTML. How can I make $teacher_body and $evaluator_body equal a file that contains the HTML that I write, and still have access to the PHP variables such as $teacher, $evaluator, $date, etc?
Example send an HTML email:
<?php
$to = "somebody#example.com, somebodyelse#example.com";
$subject = "HTML email";
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From: <webmaster#example.com>' . "\r\n";
$headers .= 'Cc: myboss#example.com' . "\r\n";
mail($to,$subject,$message,$headers);
?>
I usually use placeholders in situations like this. For example in the HTML file I'll put things like "TEACHER" and "EVALUATOR" etc. Then my PHP can be something along the lines of:
$html = file_get_contents("myFileWithPlaceholders.htm");
$html = str_replace ( "TEACHER", $teacher, $html );
$html = str_replace ( "EVALUATOR", $evaluator, $html );
Just make sure your placeholders are very unique and you should be fine.
It is highly recommended to use PHPMailer.
https://phpbestpractices.org/#email
From this best practices website:
"PHP provides a mail() function that looks enticingly simple and easy. Unfortunately, like a lot of things in PHP, its simplicity is deceptive and using it at face value can lead to serious security problems.
Email is a set of protocols with an even more tortured history than PHP. Suffice it to say that there are so many gotchas in sending email that just being in the same room as PHP's mail() function should give you the shivers.
PHPMailer is a popular and well-aged open-source library that provides an easy interface for sending mail securely. It takes care of the gotchas for you so you can concentrate on more important things."
The library can be found here:
https://github.com/PHPMailer/PHPMailer
Easy to use and works great for sending HTML and text-based emails!
This is same as sending text in email. Just add the extra tags with a dot(.) operator.
For example:
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>" . strip_tags($_POST['req-name']) . "</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>" . strip_tags($_POST['req-email']) . "</td></tr>";
$message .= "<tr><td><strong>Type of Change:</strong> </td><td>" . strip_tags($_POST['typeOfChange']) . "</td></tr>";
$message .= "<tr><td><strong>Urgency:</strong> </td><td>" . strip_tags($_POST['urgency']) . "</td></tr>";
$message .= "<tr><td><strong>URL To Change (main):</strong> </td><td>" . $_POST['URL-main'] . "</td></tr>";
$addURLS = $_POST['addURLS'];
if (($addURLS) != '') {
$message .= "<tr><td><strong>URL To Change (additional):</strong> </td><td>" .strip_tags($addURLS) . "</td></tr>";
}
$curText = htmlentities($_POST['curText']);
if (($curText) != '') {
$message .= "<tr><td><strong>CURRENT Content:</strong> </td><td>" . $curText . "</td></tr>";
}
$message .= "<tr><td><strong>NEW Content:</strong> </td><td>" .htmlentities($_POST['newText']) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
// Always set headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <webmaster#example.com>' . "\r\n";
$headers .= 'Cc: myboss#example.com' . "\r\n";
now send the email with:
mail($to, $subject, $message, $headers);
Related
OK, I have a php mailer program that works great sending html emails with total success UNLESS they contain a degree symbol or ampersand.
I imagine that it's an encoding issue but no-matter what I try the output email stops after (and including) the degree symbol.
Can I have another pair of eyes please. Here is the relevant php code:
$headers = "MIME-Version: 1.0" . "\n";
$headers .= "Content-type:text/html;charSet=utf-8" . "\n";
$headers .= "bcc: $emailList\r\n";
$headers .= "From: " . $data1. "<" . "xxx#gmail.com".">\r\n";
// next include a reply to
$headers .= "Reply-To: " . $data7 . "\r\n";
// often email servers won't allow emails to be sent to
// domains other than their own. The return path here will
// often lift that restriction so, for instance, you could send
// email to a hotmail account. (hosting provider settings may vary)
// technically bounced email is supposed to go to the return-path email
$headers .= "Return-path: " . $data7. "\r\n";
// now we can add the content of the message to a body variable
$message = "<!DOCTYPE html>";
$message .= "<html><head><title>Online test - ".$data8."</title></head><body>";
$message .= "<p style='font-family:verdana;font-size:12px;color:blue'>".$data1.", you have attempted ".$data3. " questions";
$message .= " in ".$data4." minutes and ".$data5." seconds";
$message .= " and scored a total of ".$data2.".</p>";
$message .= " <p style='font-family:verdana;font-size:12px;color:blue'>Final percentage = ".$data6."%</p>\r\n\r\n";
$message .= "<p style='font-family:verdana;font-size:12px;color:blue'>The following questions were answered incorrectly: </p><hr /><ul>";
foreach($myWrongArray as $my_Array){
$message .= "\r\n\r\n<li style='font-family:verdana;font-size:12px;color:teal'>".$my_Array."</li>";
}
//$message = strip_tags($message);
$message .= "</ul><hr /></body></html>";
// finally, send the email
mail($sendTo, $subject, $message, $headers);
So, I'm kind of in a rut for over a day now because of this issue. I have a PHP wherein it gets called by Cron on a set amount. It gets called and executes just fine without much problems except for the styling. What it does is query the database on a set time for a value and if it's true then it proceeds to email that to the designated email that I put in the script. It's doing it's job but the problem is the format when the email gets delivered. The email looks like this when I open it:
The issue, as you can see is that only the first line or row gets formatted on the table and the rest of the results doesn't follow it.
Here's the current script I'm using with some omitted/changed details.
#!/path/to/php
<?php
//DB
$dbconnect=new mysqli('localhost', 'user', 'pass', 'db');
$result=$dbconnect->query("SELECT `uid`,`pid`,`pdesc`,`umail`,`name` FROM `db_table` WHERE `pid`<='6'");
//if there are any records matching this query send an email listing each one using 'uid' as the identifier
if($result->num_rows>=1) {
$to = 'test#test.com';
$subject = "TEST FOR PRIZES NOTIFICATION";
$headers = 'From: sender#test.com' . "\r\n" .
$headers = "MIME-Version: 1.0" . "\r\n" .
$headers = "Content-type:text/html;charset=iso-8859-1" . "\r\n" .
'Reply-To: rep#test.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$message = '<html><body>';
$message .= 'THIS IS A TEST!';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= '<tr>
<td>User ID</td>
<td>Display Name</td>
<td>Email</td>
<td>Price</td>
<td>Price Description</td></tr>';
while($row=$result->fetch_assoc()) {
$message .= "<tr><td>".$row['uid']."</td>";
$message .= "<td>".$row['name']."</td>";
$message .= "<td>".$row['umail']."</td>";
$message .= "<td>".$row['pid']."</td>";
$message .= "<td>".$row['pdesc']."</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
}
if(mail($to, $subject, $message, $headers)) {
//mail successfully sent
} else {
//mail unsuccessful
}
}
?>
Thank you for your time!
You're closing the table inside of your loop, so it's closed after the first entry. Change your code from this:
while($row=$result->fetch_assoc()) {
$message .= "<tr><td>".$row['uid']."</td>";
$message .= "<td>".$row['name']."</td>";
$message .= "<td>".$row['umail']."</td>";
$message .= "<td>".$row['pid']."</td>";
$message .= "<td>".$row['pdesc']."</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
}
to this:
while($row=$result->fetch_assoc()) {
$message .= "<tr><td>".$row['uid']."</td>";
$message .= "<td>".$row['name']."</td>";
$message .= "<td>".$row['umail']."</td>";
$message .= "<td>".$row['pid']."</td>";
$message .= "<td>".$row['pdesc']."</td></tr>";
}
$message .= "</table>";
$message .= "</body></html>";
to close the table at the end.
I use a simple section of php in my header to send the contents of a mysqli query (in this case a combination of three queries - 'ORDER' has the shipping details, 'CUSTOMER' contains the email details of the customer, and 'PRODLIST' has a list of products entered into the shopping cart)
I put together the following script, trying to collect the 'ORDER' details, and add a repeating region to add all the records in the 'PRODLIST' query.
It didn't work, and I was wondering if this is even possible, and if not is there a solution that will allow me to send a simple html email with the full details?
Both queries are working by the way, they are listed on screen in the actual web page, but the mail code is not responding, and causing the page not to load.
$to = 'RECIPIENT REMOVED';
$subject = "order from " . $ORDER->getColumnVal("CUSTOMER_NAME");
$headers = "From: " . $CUSTOMER->getColumnVal("EMAIL") . "\r\n";
$headers .= "Reply-To: ". $CUSTOMER->getColumnVal("EMAIL") . "\r\n";
$headers .= "BCC: info#sigwebdesign.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";$from = "<".$CUSTOMER->getColumnVal("EMAIL").">";
$message = '<html><body>';
$message .= '<p>The following order has been received</p>';
$message .= "Delivery Type: " . $ORDER->getColumnVal("DELIVERY_TYPE") . "<br>";
$message .= "<b>Delivery Date: " . $ORDER->getColumnVal("DELIVERY_DATE") . "<br><br><br></b>";
$message .= "Company: " . $ORDER->getColumnVal("CUSTOMER_NAME") . "<br>";
$message .= "Contact: " . $ORDER->getColumnVal("PLACED_BY") . "<br><br>";
$message .= "Address: " . $ORDER->getColumnVal("DELIVERY_ADDRESS") . "<br>";
$message .= "Address: " . $ORDER->getColumnVal("CITY") . "<br>";
$message .= "Address: " . $ORDER->getColumnVal("STATE") . "<br>";
$message .= "Address: " . $$ORDER->getColumnVal("ZIP") . "<br><br><br>";
while(!$PRODLIST->atEnd()) {
$message .= "ITEM: " . $PRODLIST->getColumnVal("GENUS")." ".$PRODLIST->getColumnVal("VARIETY") . "<br>";
$message .= "QTY: " . $PRODLIST->getColumnVal("QUANTITY") . "<br>";
$PRODLIST->moveNext();
}
$PRODLIST->moveFirst();
$message .= "Total Cost: " . $_SESSION['fullcost'] . "<br><br><br>";
$message .= "This price does not include shipping, and applicable taxes. <br> Your order will be processed, and a final confirmation will be sent to you by email or by phone. <br><br>";
$message .= '</html></body>';
mail($to,$subject,$message,$headers);
So I worked it out. I added an extra "$" in the coding, and it threw a whole big spanner in the works.
so the answer (note to self at least) is check check and triple check the code!
I currently have a jquery function that has pre-written strings stored in them like this:
$('#message').val("Your parts have been ordered. We'll let you know when we receive the parts and begin installing them.");
When I click a button, it will take the string and fill it in a textarea to make filling out a form easier. It fills the textarea with the correct information and looks great on the actual form elements.
However when I'm sending the message to the client using PHPs mail function, at every ', ", and other special character it's inserting a \ before the character, so it will output like this:
Your parts have been ordered. We\'ll let you know when we receive the parts and begin installing them.
Is there a built in function that I can run the variables through before sending the email?
I've been doing some research and the closest thing I found is PHPs htmlspecialchars function, but this does the exact opposite of what I'm trying to accomplish.
Getting POST variable:
$commentmessage = mysqli_real_escape_string($conn, $_POST['message']);
Setting Headers for email (might be relevant because I'm formatting it using a table):
$headers = "From: Repairs#email.com \r\n";
$headers .= "Reply-To: ". $useremail . "\r\n";
$headers .= "CC: myemail#email.com \r\n";$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
Creating Message:
$emailmessage = wordwrap($emailmessage, 100, "\r\n");
$emailmessage = '<html><body>';
$emailmessage .= '<img src="imageurl" alt="Logo" />';
$emailmessage .= '<table rules="all" border="1" style="border-color: #666;" cellpadding="10">';
$emailmessage .= "<tr style='background: #eee;'><th colspan='2'><strong>" . $commentSubject ."</strong></th></tr>";
$emailmessage .= "<tr><td>" . $commentmessage . "</td></tr>";
$emailmessage .= "<tr><td><b>Ticket #: </b>" . $ticketid . "</td></tr>";
$emailmessage .= "</table>";
$emailmessage .= "</body></html>";
// Send Mail By PHP Mail Function
if (mail($to, $subject, $emailmessage, $headers)) {
$message = "Your mail has been sent successfully!";
}
else {
$message = "Failed to send email, try again.";
}
For PHP you have a built-in function: stripslashes().
I am collecting information through a basic HTML form. Some of the fields are arrays indicated with [] after their name.
I have successfully written to a MySQL database and I am now trying to put the array values into a PHP-generated email. The email is being sent successfully with some of the variables printing, but none of the array values are coming through. How do I go about this?
$name, $position and $email are the values I am having issues with:
<?php
$to = "myemail#email.com";
$subject = "Media Request";
$message = "A media credential request has been submitted for $outlet. The editor is $editor and their contact info is $Eemail and $phone.";
$message .= '<html><body>';
$message .= "<h2>Credential Request</h2>";
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr><td align=right><strong>Name:</strong> </td>
<td>" . strip_tags("$name") . "</td>
<td align=right><strong>Position:</strong> </td>
<td>" . strip_tags("$position") . "</td>
<td align=right><strong>Email:</strong> </td>
<td>" . strip_tags("$email") . "</td></tr>";
$message .= "</table>";
$message .= ("Here are the comments and special instructions: $notes ");
$from = "email#email.com";
$headers = "From: " . $from . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$subject,$message,$headers);
?>
Assuming you have captured the form data in the variables you mentioned, you can use one of the following methods to output the array values:
Loop through the elements
foreach ($name as $name_field) {
$message .= "Your text here. $name_field. More Text";
}
Implode() and echo
You can convert the entire array into a string in one line using implode():
$message .= "Your text here." . implode(',', $name) . "More text here";
Note:
Verify that you have the expected data in $name, $position and $email. You can do this with var_dump():
var_dump($name, $position, $email);