How to Send Email via PHP

Sending an email is one of the common actions in every programming language. In this short tutorial, we will cover how to send an email via PHP. The fastest and most efficient way of sending an email with PHP is to use the inbuilt mail function.

The syntax will look like this:

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

To be more precise, let’s consider an example of using the mail function:

<?php

  // receiver
  $to = "receiver@gmail.com";

  // subject of mail
  $subject = "w3docs.com";
	
  // text to send
  $body = "Body of your message.  You can use HTML tags  too .e.g. <br> <b> Bold </b>";

  // sender
  $headers = "From: Peter\r\n";

  // reply receiver
  $headers .= "Reply-To: info@yoursite.com\r\n";

  // content type
  $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";

  // mail function
  mail( $to, $subject, $body, $headers);

?>

Describing the Mail Function in PHP

This PHP function allows sending emails directly from the script. It is capable of returning the hash value of the parameter address. In case of a failure, it will return False.

But, you should always take into account that even when the email is accepted to be delivered, doesn’t consider that it’s already sent and got.


Do you find this helpful?

Related articles