Skip to content Skip to sidebar Skip to footer

How Do I Input Php Variables In Html Mail

Hi there I'm trying to send an HTML email through a PHP webform. The form works fine and if I pass the variables such as $name, $address in to the message it goes through ok, but w

Solution 1:

In order to get your variables into the message, if you are using double quotes, you should just be able to include the variable in the string:

eg

$message = "
<html>
...
<tr>
<td>$name</td>
</tr>
...
</html>
";

You can also break out of the string

$message = "
<html>
...
<tr>
<td>".$name."</td>
</tr>
...
</html>
";

Which will work with single or double quotes (personally I prefer this method with single quotes).

However when you receive this email, you will see the raw html. In order to have the html displayed properly you will need to set the appropriate mail headers. There are examples of how to do this here and here


Solution 2:

$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>".$firstname."</td>
<td>".$lastname."</td>
</tr>
</table>
</body>
</html>
";

Solution 3:

You should split the name into two idivdual variables e.g. $first_name and $second_name. This is possible to by doing this:

<?php

$split_names = explode(' ', $name); // assuming you have a space between both

$first_name = $split_names[0];
$last_name = $split_names[1];

?>

Then you can do this:

$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>" . $first_name . "</td>
<td>" . $second_name . "</td>
</tr>
</table>
</body>
</html>
";
 ....
?>

Solution 4:

You can do it simply like this:

$message = "
<html>
...
<tr>
<td>".htmlspecialchars($name)."</td>
</tr>
...
</html>
";

It's very import to escape content that isn't controlled by you (i.e. collected from a form) to prevent injection attacks. In this case, we use htmlspecialchars.


Post a Comment for "How Do I Input Php Variables In Html Mail"