Php-mysql Course

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 ( https://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 ( https://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="https://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 ( https://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="https://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 tag adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
Send E-mail with HTML tags and Attachment

Last accessed pages

  1. Get Time Elapsed (1884)
  2. Star shapes with CSS (11169)
  3. Calling Function and Class Method with Name from String (5745)
  4. The Prayer of the Frog (2052)
  5. jQuery Drag and Drop Rows between two similar Tables (12802)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (317)
  2. Read Excel file data in PHP - PhpExcelReader (115)
  3. The Four Agreements (96)
  4. PHP Unzipper - Extract Zip, Rar Archives (91)
  5. The Mastery of Love (85)