Get complete CodeIgniter blog project for free!

Downloaded more than 161 times, this is full project must-study for serious developers!

By submitting this form, you agree to our Terms of Service and Privacy Policy.

Send mail in PHP

Today I am going to show you how to send email using PHP. You can send mail from your server using PHP mail()  function. Let's see how to work with this function.
normally mail() function works with these parameters mail($tomail, $subject, $message, $headers)
here $tomail is targeted mail, $subject is email subject , $message is email body that means message and $headers is for mail configuration.
Here is a simple code of mail sent.

<?php
$tomail = 'yourmail[at]domain.com';
$from = 'PHPAns <admin[at]yourdomain.com>';
$subject = 'PHP Mail Check';
$headers = "MIME-Version: 1.0\ r\ n";
$headers.="Content-type: text/html; charset=iso-8859-1\ r\ n";
$headers.='From: '.$from."\ r\ n";
$message.='Hi this is phpans.com community ';
$mailsent = mail($to, $subj, $message, $headers);
mail($tomail, $subject, $message, $headers);
?>
if we will execute this script then the server will send an email from admin[at]phpans.com to info[at]phpans.com, You can change your target if you want.
Now we are going to create a script for send mail from the server. Create a file name as index.php and write down this code into this file.

index.php

<?php
if (isset($_POST['to']) && isset($_POST['subject']) && isset($_POST['message']))
{
$tomail = $_POST['to'];
$from = 'PHPAns <admin[at]phpans.com>';
$subject = $_POST['subject'];
$headers = "MIME-Version: 1.0\ r\ n";
$headers.="Content-type: text/html; charset=iso-8859-1\ r\ n";
$headers.='From: '.$from."\ r\ n";
$message.=$_POST['message'];
$mailsent = mail($to, $subj, $message, $headers);
$mail = mail($tomail, $subject, $message, $headers);
if ($mail)
{
echo 'Mail sent successfully';
}
else
{
echo 'There is an error when sending mail';
}
}
else
{
echo '<b>Mail Sender By PHPAns</b><br/>';
echo '<form method="post">';
echo 'To Mail:<br/><input name="to"><br/>';
echo 'Subject:<br/><input name="subject"><br/>';
echo 'Message:<br/><textarea name="message"></textarea><br/>';
echo '<input type="submit" value="send">';
echo '</form>';
}

?>
his script is ready for use , you need to change some value like $from as your server domain name. If you execute this script then you can send email from your server. If you will not change $from variable value then It may send mail into the spam box. So, it's most important to config with the server.

You can use mail function for the email newsletter or inform users important notice/updates about your website. Hope it will be helpful for you.






Search on PHPAns
Subscribe to PHPAns
Join with our 32000+ subscribers and get our latest articles in your email inbox for free.
Delivered by FeedBurner
We always respect your privacy and take protecting it seriously.
Connect Social With PHPAns
Top