Send simple and html email in php

Sending emails in php is quite easy. Use php function mail() to send an email.
At a minimum, mail() requires three arguments.

(1) A string containing the recipient's email address (or comma-separated list of emails if sending to multiple recipients .
(2) The email subject line, as a string.
(3) The message body, as a string.

mail() returns true if the mail was accepted for delivery by the mail server, or false if there was a problem.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

For example the following code sends a short email.

mail( "james@example.com", "Hello", "Hi James, how are you?");

You can also include the recipients real name in the recipient string, provided you follow it with the recipients email address in angle brackets.

mail( "James Franklin <james@example.com>", "Hello", "Hi James!");

The fourth optional argument of mail() specify additional header to include in the mail message.

Example of mail() with additional header.

Send Simple email in php


  $to       = 'receiver@example.com';
  $subject  = 'The subject line';
  $message  = 'Your message to send';
  $headers  = 'From: sender@example.com' . "\r\n";
  $headers .= 'To: receiver@example.com' . "\r\n" ;
  mail($to, $subject, $message, $headers);


We can also send HTML mail using mail() function. We only need to do following two things.

(1) Create the HTML markup for message body.
(2) Set an additional MIME ( Multipurpose Internet Mail Extensions ) header to indicate that the message body is in HTML format.

Send HTML email in php


  $message  = '<table width="450" border="0">
               <tr>
               <th width="150">Event</th>
               <th width="350">Date</th>
               </tr>
               <tr>
               <td>Book fair</td>
               <td>08/03/2012</td>
               </tr>
               </table>';

  $to       = 'receiver@example.com';
  $subject  = 'The subject line';

  $headers  = 'MIME-Version: 1.0' . "\r\n";
  $headers .='Content-type:text/html;charset=utf-8'."\r\n";
  $headers .= 'To: receiver@example.com' . "\r\n" ;
  $headers .= 'From: sender@example.com' . "\r\n" ;

  mail($to, $subject, $message, $headers);


This is not the end of the working of mail function. You can also send mail with attachment. You can have a look at this post.
Send simple and html email in php Send simple and html email in php Reviewed by JS Pixels on March 08, 2012 Rating: 5

1 comment:

  1. How can I handle messages I send to my users where the email address on file has since changed or shut down? I understand PhP v4.x has a "return" parameter that will return a daemon message to the sender's (me) email address if it fails to get delivered.

    How do I code this? I have tried to get it to work, but have not had any success.

    ReplyDelete

Altaf Web. Powered by Blogger.