D S Kaletha

Web Designer & Developer

How to Send Email from a PHP Script

The first thing we need to do is to write the contact form itself. Put the following code in the <body> section of an HTML file named, say, contact.html.

<form method="post" action="mail.php">
<b>Email</b> <input name="email" />
<p><b>Subject</b> <input name="subject" /> </p>
<p><b>Message</b> <textarea name="message"></textarea> </p>
<p><input type="submit" /> </p>

Now all that remains is to code "mail.php". This is made extremely easy by the facilities available in PHP. Type the following code into a file named "mail.php". Do not put anything else into that file, ie, don’t put in any other HTML tags or headers, etc

if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo ‘<div style="background-color:#ffa; padding:20px"> Invalid Input</div>’;
}
else
{//send email
$name = $_REQUEST['name'];
$email = $_REQUEST['email'] ;
$subject = "Enquiry from the Website";
$message = $_REQUEST['message']."\n**************************************\n Name – $name \n Email – $email ";
mail("example@gmail.com", "Subject: $subject",$message );
echo ‘<div style="background-color:#ffa; padding:20px"> Message Sent Succesfully , We Will get Back to You Soon ! </div>’;
//echo " $email — $subject — $message";
}
}

When the form is submitted to mail.php, the contents of the "email" field in the form is put into a PHP variable called $_REQUEST['email']. Likewise the contents of the "message" field is put into the variable $_REQUEST['message'].

If you had named the fields in your form "emailofsender" and "contentsofmessage", then the information submitted in those fields would have been available to your script in the variables $_REQUEST['emailofsender'] and $_REQUEST['contentsofmessage'] respectively. I think you get the idea.

The first thing we do in our PHP script is to make the information that is submitted easily accessible to the rest of the program.

Firstly, we made a copy of the contents of $_REQUEST['email'] in a variable we call $email. This was done in the line

 

$email = $_REQUEST['email'] ;
 

Note that we don’t really have to call this new variable $email – we could have called it $thingamajig if we wished, but it makes sense to name a variable with some meaningful name.

Likewise, in the next line, we made a copy (assigned) of $_REQUEST['message'] in a variable $message.

 

$message = $_REQUEST['message'] ;
 

Again, we could have named the new variable anything we wanted – but it’s easier for us to understand the program if the variable name reflects what it does.

The real workhorse of this script is in the line beginning with "mail"

 

mail("example@gmail.com", "Subject: $subject",$message );

Tags: , , ,

Leave a Reply