PHP send email

How can you send emails using PHP?

In PHP you can send mails through programs with using mail() function. mail() function is one of the most important function in PHP. mail() function is very easy to use. mail() function required five parameters which are mentioned below: Syntax


<?php
  mail(to,subject,message,headers,parameters);
?>
The parameters of mail function are described in below mentioned table:
Parameter Description
to This argument is mandatory. It is the receiver / receivers of the email, to whom you want to send the mail.
subject This argument is mandatory. You can write the subject of your email. Note: This argument can not contain any newline character.
message This argument is mandatory. You can write the message of your email. Each line of your mail should be separated with a \n character. Lines of your mail should not exceed 70 characters.
headers This argument is not mandatory, it is optional. This argument contains information about additional headers, like From, Cc, and Bcc. The additional headers should be separated with a (\r\n).
parameters This argument is not mandatory, it is optional. This argument contains additional parameter to the send mail program
Note: For using mail function in your PHP program so for it you will have to do some configuration settings in the php.ini file.

PHP Simple Mail Example

You can send a email very easily through PHP program with using mail() function. Example is mentioned below:

Code

<?php
  // you can write any email id, to whom you want to send the mail
  $to = "abc@example.com";     
  // you can change mail subject
  $subject = "My first mail";    
  // this would be main body of your mail
  $message = "Hello! This is a simple email message.";
  // it is a senders id    
  $from = "my@example.com";   
  $headers = "From: $from";
  mail($to,$subject,$message,$headers);
  echo "Mail Successfully Sent.";
?>
In the example above we had set some variables ($to, $subject, $message,$from, $headers), which were used as arguments for mail function for sending e-mail.

FAQ 1. Is the mail() function built into PHP? Yes, the mail() function is a built-in PHP function. You do not need to install an additional library to use it, but your server must have a properly configured mail transport. 2. Why is the PHP mail() function not working? The PHP mail() function may not work because of incorrect server configuration, missing SMTP settings, invalid sender information, or mail server restrictions. Check your PHP configuration and server mail logs to identify the problem.