Day 12 - Sending Mail From PHP - Become PHP Expert in 30 days
Sending Mail From PHP
PHP provide mail() function to sent mail from PHP scripts. Unlike many other programming languages, sending mail from PHP is very easy.
First Mail Script
day_12_ex_1.php
In following script, edit the variable $toEmail and put your email address.
You can also change $subject and $body variables.
PHP Code:
<?php
$toEmail = 'PUT YOUR EMAIL ADDR HERE';
$subject = 'WRITE SUBJECT HERE';
$body = '
Hi,
This is my test email body.
Thanks,
Day 12 Mailer
';
mail($toEmail, $subject, $body);
echo 'Mail sent to ' . $toEmail;
Once you run the script, you will get message saying Mail sent.
Since we don't provide FROM email address, it will use servers hostname.
Adding FROM Address
day_12_ex_2.php
PHP Code:
<?php
$toEmail = 'PUT YOUR EMAIL ADDR HERE';
$fromEmail = '[email protected]';
$subject = 'WRITE SUBJECT HERE';
$body = '
Hi,
This is my test email body.
Thanks,
Day 12 Mailer
';
$headers = 'From: ' . $fromEmail;
mail($toEmail, $subject, $body, $headers);
echo 'Mail sent to ' . $toEmail;
Creating A Contact Us Form
For most web sites, we will need a contact us Form to sent mail to webmaster. This will hide real email address from public. To create a contact us form, we need 2 web pages, one will show the contact us HTML form page, other will sent mail. Both can be combined into one single PHP script, but lets make 2 files, so it will be less complicated.
day_12_ex_3.html
PHP Code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
</head>
<body>
<form action="day_12_ex_3.php" method="POST">
Email<br>
<input type="text" name="fromEmail"><br>
Message<br>
<textarea name="body" cols="30" rows="10"></textarea>
<br>
<button type="submit" name="submit" value="submit">Send Mail</button>
</form>
</body>
</html>
day_12_ex_3.php
This script will handle data submitted by FORM page day_12_ex_3.htrml and sent mail to site owner. You don't have to directly access this page. If you access, script will die with out doing anything.
PHP Code:
<?php
if (isset($_POST['submit'])) {
$fromEmail = $POST['fromEmail'];
$body = $_POST['body'];
mail('[email protected]','Message from web site', $body, 'From: ' . $fromEmail . "\n\r");
echo 'Thank you for contacting us.';
} else {
die('Why are you here ? Want to hack my Script ?');
}
Exercise
Try to combine the HTML page and PHP page in example 3 into one single PHP page, this can be done by showing the HTML form page code instead of
PHP Code:
die('Why are you here ? Want to hack my Script ?');
in day_12_ex_3.php script.
http://webhostingneeds.com/tmp_fp/php-back-btn.jpg
unexpected '$body' (T_VARIABLE) error
Following error showing day_12_ex_3.php
Parse error: syntax error, unexpected '$body' (T_VARIABLE) in day_12_ex_3.php on line 5
Missing ( ; ) in
$fromEmail = $POST['fromEmail']