mail()

Contact Us or call 1-877-932-8228
mail()

mail()

PHP has a built-in mail() function that makes it easy to send email.

Mail Parameters
Parameters Description
To The address to send the email to.
Subject The email's subject.
Message The body of the email.
Additional Headers Optional. Additional headers (e.g, From, Reply-To)
Additional Parameters Optional. Any additional parameters you may want to send to your mail server.

Note: when running any script that sends out emails, you will need a mail server and access credentials. Check with your System Administrator or with your Internet Hosting Service Provider to get the mail server information.

Code Sample:

Email/Demos/Mail.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Mail()</title>
</head>
<body>
<?php
	if (!array_key_exists('Submitted',$_POST))
	{
?>
		<form method="post" action="Mail.php">
		<input type="hidden" name="Submitted" value="true">
		Mail Server: <input type="text" name="Host" size="25"><br>
		To: <input type="text" name="To" size="25"><br>
		From: <input type="text" name="From" size="25"><br>
		Subject: <input type="text" name="Subject" size="25"><br>
		<textarea name="Message" cols="50" rows="10"></textarea><br>
		<input type="submit" value="Send Email">
		</form>
<?php
	}
	else
	{
		ini_set('SMTP',$_POST['Host']);
		$to = $_POST['To'];
		$from = 'From: ' . $_POST['From'];
		$subject = $_POST['Subject'];
		$message = $_POST['Message'];
	
		if(mail($to,$subject,$message,$from))
		{
			echo "Message Sent";
		}
		else
		{
			 echo "Message Not Sent";
		}
	}
?>
</body>
</html>

For this example to work, you will need to have a mail server set up on your server.

The first time a visitor hits the page, he'll be presented with a form. When the user fills out and submits that form, the mail() function will attempt to send an email to the address the user entered.

Note that the mail server is set with the ini_set() function, which is used to temporarily change configuration settings. You can set the default mail server in the php.ini file with the SMTP setting.

Shortcomings of mail()

The mail() function has many limitations.

  • No support for SMTP authentication.
  • Difficult to send HTML-formatted emails.
  • Difficult to add attachments.

Luckily, there are extensions that do provide these features.

Next