SENDING EMAILS VIA MAIL( ) FUNCTION IN PHP FOR BEGINNERS
Introduction: Mail() function is one of the best function/method among several functions in PHP that does a complicated task in an easy and better way. It's a function responsible for sending mails to users. The mail() function allows you to send emails directly from a script. The goal of this article is to show you the step-by-step guide to sending mails through PHP's mail().
STEP-BY-STEP GUIDE TO SENDING EMAIL IN PHP
- Use the PHP mail function i.e mail( );
- Include parameters into the PHP mail( ) function e.g
mail($to, $subject, $body, $header).
- $to = this variable contains the email address that will receive
the email when sent. - $subject = contain the subject of the email.
- $body = contain the message that's about to be sent.
- $header = contain the email of the sender.
Below is the code sample on how to send an email via PHP mail() method:
// Note: In PHP, you get an input value by getting the name attribute. So the submit button is gotten from the name attribute in the form.
// ---------------------------------------------------------------------------
// if submit button in the form is clicked:
if (isset($_POST['submit_btn'])) {
// --------------------------------------------------------------------
//get the subject of the email
$subject = $_POST['subject'];
//get the content of the email
$body = $_POST['body'];
//get the email address of the sender
$myEmail = $_POST['email'];
//get the sender of the mail
$header = 'From: '.$myEmail;
//reciever of the mail
$to = 'joseph@gmail.com'
// --------------------------------------------------
// send the email
mail($to, $subject, $body, $header);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="post">
<input type='text' name="subject" placeholder="enter subject"><br><br>
<input type='text' name="body" placeholder="enter content"><br><br>
<input type='email' name="email" placeholder="your email"><br><br>
<input type='submit' name="submit_btn" value="Contact">
</form>
</body>
</html>