How to make mail php

Build a secure PHP email system with an example – learn how to easily create a reliable system to send and receive emails.

Creating a PHP Mail

Mail can be sent using the mail() function in PHP. This function can be used to send emails from scripts running on a server. Before you can use this function, you need to ensure that your server is configured to send emails.

The syntax of the mail() function is as follows:

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

Where,

  • $to – The email address of the recipient.
  • $subject – The subject of the email.
  • $message – The message body of the email.
  • $headers – Optional additional headers.

Let’s see an example of the mail() function in action. This example shows how to send a simple email message:


<?php
  $to = '[email protected]';
  $subject = 'This is an example email';
  $message = 'This is the body of the email message.';
  $headers = 'From: [email protected]';
  mail($to, $subject, $message, $headers);
?>

In the above example, the $headers argument is used to set the sender’s email address. This is important because if it is not set, the mail will be sent from the server’s default address. This can cause problems if the recipient’s email server rejects messages from unknown senders.

You can also include additional headers in the $headers argument. For example, you can set the Cc and Bcc headers to send a copy of the message to multiple recipients. To do this, you need to separate the headers with a carriage return and new line:


$headers = 'From: [email protected]' . "rn" .
           'Cc: [email protected]' . "rn" .
           'Bcc: [email protected]';

You can also include additional headers such as Reply-To and Content-Type in the $headers argument.

Once the mail() function is called, the email will be sent. If it is successful, the function will return true. However, if an error occurs, the function will return false and an error message will be written to the server’s error log file.

In summary, the mail() function in PHP can be used to send emails from scripts running on a server. It takes four arguments which are the recipient’s email address, the subject, the message body and any additional headers. The function will return true if the email is sent successfully, or false if an error occurs.

Answers (0)