Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
css
php
php mail()
communitycreator

How to send an email using a PHP function

Behzad Ahmad

Overview

We can use the mail() function in PHP to send emails. This function requires three necessary parameters. First of all, we specify the email to which we have to send the mail. Secondly, we specify the subject of the message. Lastly, we write the actual message which we want to send. There are also two other optional parameters.

Syntax

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

Parameters

  • to: This is a required field. In this, we have to specify the recipient/recipient’s email address.

  • subject: This is a required field. In this, we have to specify the subject line of our email.

  • message: This is also a required field. In this field, we have to write the message we want to send. We cannot exceed the line by 70 characters. To separate the line, we use LF(\n).

  • headers: This is an optional field. In this, we specify any additional headers like Cc, Bcc, and so on. To separate the headers, we use CRLF(\r\n).

  • parameters: This is an optional field. It is used to send the optional parameters.

Code

The following is the basic code to demonstrate the use of the PHP mail() function:

<?php
   $to = "abc@gmail.com";
   $subject = "This is just a Testing mail";
         
   $message = "<b>HTML Message</b>";
   $message .= "<h1>Some Heading</h1>";
         
   $header = "From:xyz@gmail.com\r\n";         
   $temp = mail ($to,$subject,$message,$header);
         
   if( $temp == true ) 
   {
      echo "Mail Sent";
   }
   else 
   {
      echo "Unable to Send Mail";
   }
?>

Explanation

  • Line 2: We write the email address to which we have to send the mail.

  • Line 3: We write a subject for the mail.

  • Lines 5 and 6: We write the message to be sent in the mail.

  • Line 8: We specify from which email address we want to send the mail.

  • Line 9: We pass all the arguments to the PHP mail() function and store its value in a variable.

  • Lines 11 to 18: We check if the function returns true when the message is printed, which states that the mail is sent. Otherwise, it states that it is unable to send mail.

RELATED TAGS

html
css
php
php mail()
communitycreator
RELATED COURSES

View all Courses

Keep Exploring