How to send email in PHP with example

Send email in PHP using HTML form inputs

Before sending the emails, we must know the syntax of the mail() function as shown below

<!DOCTYPE html> <html lang="en">
<head>
<title></title>
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="width: 40%;"> <br><br>
<h3>Send Email in PHP</h3>
<form method="post" action="send.php">
<div class="form-group">
<label for="email">Subject:</label>
<input type="text" name="subject" class="form-control form-control-sm"> </div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control form-control-sm" name="email"> </div>
<div class="form-group">
<label for="email">Message:</label>
<textarea name="message" class="form-control form-control-sm" rows="5"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="send">Send</button>
</div>
</form>
</div>
</body>
</html>
<?php 
if(isset($_POST['send']))
{
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
//set the email
$headers = "From: Sender Address senderemail\r\n";
$headers .= "Reply-To: senderemail\r\n";
$headers .= "Return-Path: senderemail\r\n";
//send the email
if(mail($to, $subject, $message, $headers))
{
echo 'Email has been sent';
}
else
{
echo 'Email could not send';
}
}
?>

--

--

Hi, This is Biplab and I am web developer well versed in PHP and other open source technologies. I am here to share my experience with the community.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store