Sending email from a webpage using PHP

Categories Web HostingScriptingPHP Tags html

Any PHP script which uses the mail function to send emails will work on our Linux servers. If you are having difficulties creating a contact form and FormMail does not suit your needs, you are welcome to use the below example code as a starting point for your email form.

Please note that this example is provided as is and we aren't able to provide you support in modifying your email form to include additional functionality.

If you require additional coding assistance, we recommended visiting php.net.

Example form

<?php
$message = '';

if (isset($_POST['email']) && !empty($_POST['email'])){
  if (mail($_POST['email'], $_POST['subject'], $_POST['body'], "From: name@yourdomain.com")){
    $message = "Email has been sent to <b>".$_POST['email']."</b>.<br>";
  }else{
    $message = "Failed sending message to
 <b>".$_POST['email']."</b>.<br>";
  }
}else{
  if (isset($_POST['submit'])){ 
$message = "No email address specified!<br>";
  }
} 

if (!empty($message)){
   $message .= "<br><br>";
 }
 ?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
Mail test
</title>
</head>
<body>
<?php echo $message; ?>
<form method="post" action="">
<table>
<tr>
<td>
e-mail
</td>
<td>
<input name="email" value="<?php if (isset($_POST['email'])
&& !empty($_POST['email'])) echo $_POST['email']; ?>">
</td>
</tr>
<tr>
<td>
subject
</td>
<td>
<input name="subject">
</td>
</tr>
<tr>
<td>
message
</td>
<td>
<textarea name="body"></textarea>
</td>
</tr>
<tr>
<td>
&nbsp;
</td>
<td>
<input type="submit" value="send" name="submit">
</td>
</tr>
</table>
</form>
</body>
</html>

Rate this article