Clue Mediator

Send an email using PHP mail() function

📅January 30, 2020
🗁PHP

In this article, we will explain to you how to send an email using PHP mail() function with simple text or html.

Core php mail function, php mail function, php mail() function,Sending Emails in PHP, How to Setup the PHP mail() Function, How to Send Email using PHP mail() Function, php mail function not working, php send email form, Sending email with html content.

Checkout more articles on PHP

PHP provides an in-built `mail()` function to send email. In this function, three parameters are required and rest of the parameters are optional.

Syntax:

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

Let's look about the parameters.

  • to: It's required parameter and we have to add receiver email id. Also we can add multiple email ids by comma separated.
  • subject: It's a required parameter. It specified the subject of the email.
  • message: It's also required parameter. It specified the message of the email.
  • headers: It's optional parameter and we can add additional headers i.e. From, CC, BCC that must be separated by (/r/n).
  • parameters: It's also an optional parameter and used to pass additional parameters.

This function returns true if email sent successfully and false if email failed.

Sending simple email

<?php
	$to = "[email protected]";
	$subject = "Test Mail";
	$message = "Hi, This is a test mail using php";

	if (mail($to, $subject, $message)) {
		echo("Your email successfully sent");
	} else {
		echo("Your email is not sent");
	}
?>

// Output: Your email successfully sent

Sending email with html message

<?php
	$to = "[email protected]";
	$subject = "Test Mail";
	$message = "Hi, This is a test mail using php";

	$headers = "From:[email protected] \r\n";
	$headers .= "Cc:[email protected] \r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html\r\n";

	if ( mail($to, $subject, $message, $headers)) {
		echo("Your email successfully sent");
	} else {
		echo("Your email is not sent");
   }
?>

// Output: Your email successfully sent

Note: PHP mail() function will not work in Local server. If you want to make it work then you have to configure SMTP authentication.

That’s it for today.
Thank you for reading. Happy Coding!