This tutorial shows how to send emails with HTML tags, and attachament with the mail() function in PHP.
- To can use the mail() function to send emails with PHP, the server must run a mail server, which is separately by PHP.
Generally, to send e-mail with mail() function, it uses this syntax:
mail($receiver_address, $subject, $message, $sender_address)

Send E-mail with HTML tags

To send mails with HTML tags that will be recognized and formated in the maessage, you must add these two lines of code in the mail header, that tell the email server to recognize the message as HTML text:
"MIME-Version: 1.0\r\n";
"Content-type: text/html; charset=iso-8859-1\r\n"

Here's a simple function that can be used in PHP scripts to send mail with HTML tags:
function sendMail($to, $from, $from_name, $sub, $msg){
 // Send mail with HTML tags ( http://coursesweb.net/ )
  $eol = "\r\n";             // to add new row

  // Define the headers for From and HTML
  $headers = "From: " . $from_name . "<" . $from . ">".$eol;
  $headers .= "MIME-Version: 1.0" . $eol;
  $headers .= "Content-type: text/html; charset=iso-8859-1" . $eol;

  // sends data to mail server.
  // Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise
  if (mail($to, stripslashes($sub), stripslashes($msg), $headers)) return true;
  else return false;
}

- The HTML tags can also contain inline CSS style.
- Example of using the sendMail() function, displayed above:
<?php
function sendMail($to, $from, $from_name, $sub, $msg){
 // Send mail with HTML tags ( http://coursesweb.net/ )
  $eol = "\r\n";             // to add new row

  // Define the headers for From and HTML
  $headers = "From: " . $from_name . "<" . $from . ">".$eol;
  $headers .= "MIME-Version: 1.0" . $eol;
  $headers .= "Content-type: text/html; charset=iso-8859-1" . $eol;

  // sends data to mail server.
  // Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise
  if (mail($to, stripslashes($sub), stripslashes($msg), $headers)) return true;
  else return false;
}


// Define variable with data to pass to sendMail()

$to = 'receiver@example.com';           // receiver of the mail
$from = 'sender@domain.net';            // sender e-mail address
$from_name = 'Sender Name';
$subject = 'Subject of the mail';
$message = '<h3>Message from CoursesWeb</h3>
  <div style="color:blue;">If you want to learn  <b>web programming languages</b>,<br />
  Try study <em>the lessons and tutorials</em> from: <a href="http://coursesweb.net/" title="Web Programming">coursesweb.net</a></div>';

// Calls the sendMail() to send mail, outputs message if the mail was accepted for delivery or not
if(sendMail($to, $from, $from_name, $subject, $message)) {
  echo 'The mail successfully sent';
}
else echo 'The mail cannot be send';
?>

Send E-mail with Attachments

To include one, or more attachaments into a mail sent with PHP, the code is a little more complicated. Data of the file for attachament must be read by PHP, coded with MIME base64, then split with the chunk_split() function. These data, and the type of the attached file are added in the message body.
- Here's a function that can be used in PHP scripts to send mails with attachament (also with HTML tags). Example and explanations are in the code:
<?php
$attach = array();              // will contain data for attachments
function sendMailAtt($to, $from, $sub, $msg, $attach=array()) {
 // Send mail with Attachments, and HTML tags ( http://coursesweb.net/ )
  // Define the headers
  $headers = "From: ".$from;

  $rand_hash = md5(time());
  $mime_boundary = "==Multipart_Boundary_x".$rand_hash."x";

  $headers .= "\nMIME-Version: 1.0\n".
    "Content-Type: multipart/mixed;\n".
    ' boundary="'.$mime_boundary.'"';

  $msg .= "Multi-part message in MIME format.\n\n".
    '--'.$mime_boundary."\n".
    "Content-Type:text/html; charset=\"iso-8859-1\"\n".
    "Content-Transfer-Encoding: 7bit\n\n".$msg."\n\n";

  // If there are data for attachments, include each attachment in message
  if (count($attach)>=1) {
    // traverse the array with data for file to attach
    for($i=0; $i<count($attach); $i++) {
      // Open the file and read its data
      if ($file = fopen($attach[$i][0],'rb')) {
        $data = fread($file, filesize($attach[$i][0]));
        fclose($file);
      }

      // Code the file data with MIME base64, and split in small chunks
      $data = chunk_split(base64_encode($data));

      // Add file data in mail message
      $msg .= '--'.$mime_boundary."\n".
      'Content-Type: '.$attach[$i][1].";\n".
      ' name="'.basename($attach[$i][0])."\"\n".
      "Content-Transfer-Encoding: base64\n\n".$data ."\n\n".
      '--'.$mime_boundary."\n";
    }
  }

  // sends data to mail server.
  // Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise
  if(mail($to, $sub, $msg, $headers)) return true;
  else return false;
}

    /* Using sendMailAtt() */
// Define variable with data to pass to sendMailAtt()

$to = 'receiver@example.com';           // receiver of the mail
$from = 'sender@domain.net';            // sender e-mail address
$subject = 'Subject of the mail';
$message = '<h3>Message from CoursesWeb</h3>
  <div style="color:blue;">If you want to learn <b>web programming languages</b>,<br />
  Try study <em>the lessons and tutorials</em> from: <a href="http://coursesweb.net/" title="Web Programming">coursesweb.net</a></div>';

// Attach two files: an image and a zip archive
// - Each element contains: "file path", "file mime type"
$attach[] = array('image.jpg', 'image/jpeg');
$attach[] = array('archive.zip', 'application/octet-stream');

// Calls the sendMailAtt() to send mail, outputs message if the mail was accepted for delivery or not
if(sendMailAtt($to, $from, $subject, $message, $attach)) {
  echo 'The mail successfully sent';
}
else echo 'The mail cannot be send';
?>

- The message in the mail sent with the sendMailAtt() function (defined in the code above) can also contains HTML tags and inline CSS style.
- The attachament is optional, so, you can use it to send mails with, or without attachament; in this case, the $attach[] can be deleted.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which meta tag provides a short description of the page?
<meta content="..."> <meta description="..."> <meta http-equiv="...">
<meta name="description" content="70-160 characters that describes the content of the page" />
Which CSS property is used to stop the wrapping effect of the "float"?
clear text-align position
#some_id {
  clear: both;
}
Click on the method which gets an array with all the elements in the document that have a specified tag name.
getElementsByName() getElementById() getElementsByTagName()
var divs = document.getElementsByTagName("div");
var nr_divs = divs.length;
alert(nr_divs);
Indicate the PHP function which returns the number of elements in array.
is_[) count() strlen()
$arr =[7, 8, "abc", 10);
$nri = count($arr);
echo $nri;        // 4
Send E-mail with HTML tags and Attachment

Last accessed pages

  1. Simple Admin Login PHP Script (587)
  2. PuzzleImg - Script to Create Image Puzzle Game (1805)
  3. Editing, Changing XML - E4X (1002)
  4. Select in MySQL, Output results in HTML Table (696)
  5. Qwop (60365)

Popular pages this month

  1. Qwop (5845)
  2. Drag Racer V3 (2771)
  3. Flash Games - Free online Games (1439)
  4. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (1246)
  5. Bubbles3 (1115)