Sunday, October 1, 2017

PHP Mail

skptricks PHP Mail

PHP mail() function is used to send email in PHP. You can send text message, html message and attachment with message using PHP mail() function.

PHP mail() function:

Syntax:

bool mail string $to string $subject string $message [, string $additional_headers [, string $additional_parameters ]] ) 
$to :
Here we are providing receiver or receivers of the mail. The receiver must be specified one of the following forms:
  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>
$subject: 
Here we are providing subject of the mail.

$message: 
Here we are providing message of the mail to be sent.

Note : Each line of the message should be separated with a CRLF ( \r\n ) and lines should not be larger than 70 characters.

additional_headers (optional)

String to be inserted at the end of the email header.
Note : This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

PHP Mail Function example :

<?php  
   ini_set("sendmail_from""skptricks@gmail.com");  
   $to "skptricks@gmail.com";//change receiver address  
   $subject "This is subject";  
   $message "This is simple text message.";  
   $header "From:skptricks@gmail.com \r\n";  
  
   $result mail ($to,$subject,$message,$header);  
  
   if( $result == true ){  
      echo "Message sent successfully...";  
   }else{  
      echo "Sorry, unable to send mail...";  
   }  ?>

PHP Mail: Sending mail with extra headers:

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

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

PHP Mail: Send HTML Message:

To send HTML message, you need to mention Content-type text/html in the message header.

<?php  
   $to "abc@example.com";//change receiver address  
   $subject "This is subject";  
   $message "<h1>This is HTML heading</h1>";  
  
   $header "From:xyz@example.com \r\n";  
   $header .= "MIME-Version: 1.0 \r\n";  
   $header .= "Content-type: text/html;charset=UTF-8 \r\n";  
  
   $result mail ($to,$subject,$message,$header);  
  
   if( $result == true ){  
      echo "Message sent successfully...";  
   }else{  
      echo "Sorry, unable to send mail...";  
   }  ?>

No comments:

Post a Comment