Php-mysql Course

To send e-mails directly from a PHP script, you can use the mail() function.

  - Syntax:
mail(to, subject, body, headers);
- to - a string with the address(es) of the receiver(s). Can be in either of the following formats:
                "name@domain.com"       or       "Some Name <name@domain.com>"
To send to more than one address, use a comma-separated string like this:
                "user@domain.com, another@domain.com, Some Name <name@domain.com>"
- subject - the email's subject line.
- body - is where you put the contents of the email. It must be presented as a single string. New lines must use both a carriage return (\r) and newline character (\n), "\r\n", and the lines should not be larger than 70 characters.
To wrap text to 70 characters, you can use wordwrap() function. It adds a new line every X characters:
                $body = wordwrap($body, 70);
- headers - optional, it's a string used to add extra headers (From, Reply-To, Cc, Bcc, encoding). Each new header, except the final one, should be separated with a "\r\n".
It is recommended that you always include a From value in the "headers" parameter.

mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.
• This function doesn't send the email itself. It just transfers email data to a mail server running on the computer, and actually that server sends the email. The computer on which PHP is running must have a working mail server in order for this function to work. But PHP has no way of knowing if the email is delivered to the destination.

Simple form contact script

Usually, data for the mail() function arguments, especially for "body", is received from an HTML form.
  Here is an example of a simple php mail script for a contact form. Sends a text mesage from a form to a specified e-mail address.
<?php
$to = 'your_email@domain.com';          // receiver address

// Check for form submission
if (isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
  // get form data
  $from = 'From: '. $_POST['email'];
  $subject = $_POST['subject'];
  $body = $_POST['message'];
  $body = wordwrap($body, 70);           // makes the body no longer than 70 characters long

  // send the email
  if (mail($to, $subject, $body, $from)) echo 'Thank you for using our mail form';
  else echo 'Error, the message can not be sent';
}
?>

<form action="" method="post">
 E-mail: <input type="text" name="email" /><br />
 Subject: <input type="text" name="subject" /><br />
 Message:<br />
 <textarea name="message" rows="8" cols="30"></textarea><br />
 <input type="submit" value="Send" />
</form>
- First, this script checks if the "email", "subject" and "message" fields are filled out. Gets data from these fields and use the mail() function to send the email, and returns a message for success or error.
- $to variable contains the address where the e-mail will be sent.

Validate email address, filter form data and set headers

The script above is the simplest way to send e-mail, but it is not secure. For example, it should check if the user has completed all fields, also, to validate email address, and other filters.
By default, mail() uses Latin1 (ISO-8859-1) encoding, which doesn't support accented characters. But the Unicode (UTF-8) supports most written languages, including the accents commonly used in European languages.
To ensure that email messages display correctly accents and less usual characters, use the Content-Typeg header to set the encoding to UTF-8 like this:
                $headers = "Content-Type: text/plain; charset=utf-8\r\n";
Another usefull header is Reply-To, this set an address for Reply.
                $headers = "Reply-To: an_email@domain.com";

• Here is a more complete and secure contact form script. It removes tags from form data, checks to be a valid e-mail address, and a minimum number of characters for "subject" and "message". Also, it adds the "From", "Conten-Type" (utf-8), and "Reply-To" headers in the email (for more explanations, see the comments in the script).
<?php
$to = 'your_email@domain.com';          // receiver address

$erors = array();                      // set an empty array that will contains the errors
$regexp_mail = '/^([a-zA-Z0-9]+[a-zA-Z0-9._%-]*@([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4})$/';         // an e-mail address pattern

// Check for form submission
if (isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
  // remove tags and whitespace from the beginning and end of form data
  $_POST = array_map("strip_tags", $_POST);
  $_POST = array_map("trim", $_POST);

  // chech if all form fields are filled in correctly
  // (email address and the minimum number of characters in "subject" and "message")
  if (!preg_match($regexp_mail, $_POST['email'])) $erors[] = 'Invalid e-mail address';
  if (strlen($_POST['subject'])<3) $erors[] = 'Subject must contain minimum 3 characters';
  if (strlen($_POST['message'])<5) $erors[] = 'Subject must contain minimum 5 characters';

  // if no errors ($error array empty)
  if(count($erors)<1) {
    // get form data
    $from = 'From: '. $_POST['email'];
    $subject = $_POST['subject'];
    $body = $_POST['message'];
    $body = wordwrap($body, 70);           // makes the body no longer than 70 characters long

    // set headers (From, Encoding utf-8 and Reply-to)
    $headers = $from. "\r\n";
    $headers .= 'Content-Type: text/plain; charset=utf-8';
    $headers .= "Reply-To: ". $_POST['email'];

    // send the email
    if (mail($to, $subject, $body, $headers)) echo 'Thank you for using our mail form';
    else echo 'Error, the message can not be sent';
  }
  else {
    // else, if errors, it adds them in string format and print it
    echo implode('<br />', $erors);
  }
}
?>

<form action="" method="post">
 E-mail: <input type="text" name="email" /><br />
 Subject: <input type="text" name="subject" /><br />
 Message:<br />
 <textarea name="message" rows="8" cols="30"></textarea><br />
 <input type="submit" value="Send" />
</form>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
}
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
alert(content);
Click on the "echo" correct instruction.
echo "CoursesWeb.net" echo "CoursesWeb.net"; echo ""CoursesWeb.net";
echo "Address URL: http://CoursesWeb.net";
PHP Sending E-mails

Last accessed pages

  1. Register and show online users and visitors (39381)
  2. Get Mime Type of file or string content in PHP (6075)
  3. The Mastery of Love (6785)
  4. Get visitor IP in PHP (1192)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (137599)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (288)
  2. Read Excel file data in PHP - PhpExcelReader (100)
  3. The Four Agreements (88)
  4. PHP Unzipper - Extract Zip, Rar Archives (86)
  5. The Mastery of Love (82)