Sending Simple Email with PHP
Basics of PHP – Part 18
Forward: In this part of the series, I talk about Sending Simple Email with PHP.
By: Chrysanthus Date Published: 29 Jul 2012
Introduction
Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.
The sendmail Binary
The sendmail program is called the sendmail binary. The sendmail binary must be install in your server; the system administrator should do this. The user of the form should have permission to use the sendmail binary; the system administrator should take care of that.
Typical Email
A typical email has the subject value, To value (email address), From value (email address), Date value and the message. The Subject, To, From and Date values are in the header of the email. The message is like the body of the email. You can also have optional headers like the Cc and Bcc.
Sending a simple mail is easy if your system administrator has done his job. All you have to do is to know how to use the predefined PHP mail function. In simple terms, the syntax of the mail function is:
mail ( string $to, string $subject , string $message [string $additional_headers] )
The first parameter, $to, is the email of the recipient as a string. The second parameter, $subject, is the subject as a string. The third parameter, $message, is the message as a string.
Now, in the message, there should be no line longer than 70 characters. To convert all the lines to at most 70 characters each, you have to do this:
$message = wordwrap($msgVar, 70);
wordwrap() is a predefined function. It converts the text message from the web form, into at most 70 characters per line. Its first argument is the complete message string. Its second argument in this case is 70. The return value will be the third parameter in the mail function parentheses.
The fourth parameter for the mail function is optional. It is a string. Even though it is optional, it is advisable to always use it. It should have at least the From and Date headers. It can also have the Cc and Bcc headers. The headers are separated by the text, “\r\n”. You can have something like:
"From: him@hisserver.com \r\n Date: 05-06-2009"
The strings of all the above arguments of the mail function are prepared and assigned to variables. The mail function is called fitting these variables as argument. The example below illustrates this.
In this section I explain the process the web form content takes until it reaches the sendmail binary. When the information reaches the sendmail binary, it is no longer your business, as the sendmail binary will sent it to the destination email box.
The web form has fields, some of which are required (most be filled) and others are not required. In the example below, the form at the browser will call the web page at the server that has the form (the page calls itself). When the page is called, PHP code scripts will validate the required fields. If all the fields are OK, then the PHP mail function will be called. When the mail function is called, it hands over everything to the sendmail binary. The system administrator should have done all the preparation for the sendmail binary to receive the formatted information. This is the code segment that prepares the mail function arguments variables:
$to = $_POST["recipient"];
$subject = $_POST["subject"];
$message = $_POST["msg"];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST["email"] . "\r\n" . "Date: " . date("m-d-Y,H:i:s");
In the following example, there is a PHP variable at the global scope. This variable is called, $allFieldsOK. It initially has the value, true. If any PHP code script finds out that its corresponding field is not correct, it sets the value of this variable to false. Before the PHP mail function is called, an if-statement checks if the value of the variable is true. If it is true, the mail function is called. If it is not true, the mail function is not called. Whether the form fields are OK or not, since the form calls its own page at the server on submit, the page will still be sent back from the server to the browser. You can write code using PHP and JavaScript that will indicate to the page sent back that the form content has been sent (to sendmail). This is the code segment that sends the formatted content:
if ($allFieldsOK == true)
{
mail($to, $subject, $message, $headers);
echo "<span style='color:red; font-weight:bold' name='Success'>Thank you! You message has been sent.</span>";
}
Note that the email address the mail is sent to is in a hidden Input control of the web form. The form and the PHP code are on one page. Also note that the date is generated by the PHP page (code) at the server.
When the form submit button is clicked, the name/value pairs of the form controls will arrive at the PHP page at the server. These name/value pairs at the server become the key/value pairs of the $_POST array of the page. PHP code uses these key/value pairs to form the variables for the mail function.
The $header string is formed by concatenating strings using the dot operator.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>
<form method="post" action="myfile.php">
Fields marked with * are required.<br /><br />
<input type="hidden" name="recipient" value="destination@someserver.com">
<p id="P1" style="color:red; display:none">One or more Field Content is not correct!</p>
<?php
$allFieldsOK = true;
?>
<?php
if ($_POST["userName"] == "")
{
echo "<span style='color:red' name='PHPSpan'>The Name Field cannot be empty!</span><br />";
$allFieldsOK = false;
}
?>
*Name: <input type="text" name="userName"> <br /><br />
<?php
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
{
echo "<span style='color:red' name='PHPSpan'>The Email Field Content is not correct!</span><br />";
$allFieldsOK = false;
}
?>
*Email: <input type="text" name="email"> <br /><br />
<?php
if (!filter_var($_POST["url"], FILTER_VALIDATE_URL))
{
echo "<span style='color:red' name='PHPSpan'>The URL Field Content is not correct!</span><br />";
$allFieldsOK = false;
}
?>
Your Web Site URL: <input type="text" name="url"> <br /><br />
Address <input type="text" name="address"> <br /><br />
<?php
if ($_POST["subject"] == "")
{
echo "<span style='color:red' name='PHPSpan'>The Subject Field cannot be empty!</span><br />";
$allFieldsOK = false;
}
?>
*Subject <input type="text" name="subject"> <br /><br />
<?php
if ($_POST["msg"] == "")
{
echo "<span style='color:red' name='PHPSpan'>The Message Field cannot be empty!</span><br />";
$allFieldsOK = false;
}
?>
*Message: <textarea name="msg" rows="3" cols="30"></textarea><br /><br />
<button type="submit">Send</button>
</form>
<?php
$to = $_POST["recipient"];
$subject = $_POST["subject"];
$message = $_POST["msg"];
$message = wordwrap($message, 70);
$headers = "From: " . $_POST["email"] . "\r\n" . "Date: " . date("m-d-Y,H:i:s");
if ($allFieldsOK == true)
{
mail($to, $subject, $message, $headers);
echo "<span style='color:red; font-weight:bold' name='Success'>Thank you! You message has been sent.</span>";
}
?>
<script type="text/javascript">
spanRef = document.getElementsByName('PHPSpan');
if (spanRef.length > 0)
document.getElementById('P1').style.display = "block";
</script>
</body>
</html>
One of the things you should note in this code is that a PHP script can see what is in another PHP script.
In the course of the user filling in the form, some fields might have the required syntax and others might not. You may write the code in such a way that those that are correct will be sent back to the browser, so that the user will not have to retype them.
We stop here and continue in the next part of the series.
Chrys
Related Links
Major in Website DesignWeb Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course
NEXT