Open In App

PHP | Sending mails using mail() function

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

PHP is a server side scripting language that is enriched with various utilities required. Mailing is one of the server side utilities that is required in most of the web servers today. Mailing is used for advertisement, account recovery, subscription etc.

In order to send mails in PHP, one can use the mail() method.

Syntax:

bool mail(to , subject , message , additional_headers , additional_parameters)

Parameters: The function has two required parameters and one optional parameter as described below:

  • to: Specifies the email id of the recipient(s). Multiple email ids can be passed using commas
  • subject: Specifies the subject of the mail.
  • message: Specifies the message to be sent.
  • additional-headers(Optional): This is an optional parameter that can create multiple header elements such as From (Specifies the sender), CC (Specifies the CC/Carbon Copy recipients), BCC (Specifies the BCC/Blind Carbon Copy Recipients. Note: In order to add multiple header parameters one must use ‘\r\n’.
  • additional-parameters(Optional): This is another optional parameter and can be passed as an extension to the additional headers. This can specify a set of flags that are used as the sendmail_path configuration settings.

Return Type: This method returns TRUE if mail was sent successfully and FALSE on Failure.

Examples:

  1. Sending a Simple Mail in PHP




    <?php
      $to = "recipient@example.com";
      $sub = "Generic Mail";
      $msg="Hello Geek! This is a generic email.";
      if (mail($to,$sub,$msg))
          echo "Your Mail is sent successfully.";
      else
          echo "Your Mail is not sent. Try Again.";
    ?> 

    
    

    Output :

    Your Mail is sent successfully.
    
  2. Sending a Mail with Additional Options




    <?php
      $to = "recipient@example.com";
      $sub = "Generic Mail";
      $msg = "Hello Geek! This is a generic email.";
      $headers = 'From: sender@example.com' . "\r\n" .'CC: another@example.com';
      if(mail($to,$sub,$msg,$headers))
          echo "Your Mail is sent successfully.";
      else
          echo "Your Mail is not sent. Try Again.";
    ?> 

    
    

    Output :

    Your Mail is sent successfully.
    

Summary:

  • Using mail() method one can send various types of mails such as standards, html mail.
  • The mail() method opens the SMTP socket, attempts to send the mail, closes the socket thus is a secure option.
  • mail() method should not be used for bulk mailing as it is not very cost-efficient.
  • The mail() method only checks for parameter or network failure, thus a success in the mail() method doesn’t guarantee that the intended person will receive the mail.


Last Updated : 08 Mar, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads