PHP code to send email using PHP mail function

In this article I am going to share the PHP code to send email using PHP mail function.
Nowadays every website has contact form to receive customers query through website contact form.
Actually this is a good idea to collect your visitors information so that later you can contact them regarding your products & solution.You can easily implement contact form on your website by writing 10 lines of code.
Though I am not good at  memorizing the code and that’s why I am sharing the php mail code here so that I can just copy paste the code and use it anywhere.

PHP code to send email using PHP mail function

<?php

    $headers  = "From: arvind@xpertztech.com\r\n";
    $headers .= "Reply-To: arvind@xpertztech.com\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
    //$headers .= "Date: " . $_POST['Date'] . "\r\n";
    $headers .= "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";        
    $subject="Test Mail";
    $to='arvind@xpertleague.com';
    $msg="Test Mail, Please Ignore";    
    if(mail($to, $subject, $msg, $headers))
        echo 'Success';  
    else 
        echo 'Failed';  
?>

PHP mail code is self explanatory but if you are new to PHP let’s analyse the code line by line.
Line 1: In first line of code, we are declaring the header of email and including the email from which we want to send the mail.
Line 2: In second line we are adding “Reply To” email, you can skip this part if from email and receiving email is same.
Line 3: In third line we are adding the Mailer info in the header, this is not required, you can skip this in your script.
Line 4: In fourth line we are adding receiving date of email, this is also optional you can skip this line too.
Line 5-6: In fifth and sixth, line we are declaring mime version and type, this field is required if you want to add html code in your message and render them in email.
Line 7: In line seven, we are adding subject of email.
Line 8: Line eight declares the recipient of mail to which you want to send the mail.
Line 9: Line nine declares the message, which we want to send.
Line 10: In this line we are using if to check whether mail delivered successfully or not, you can skip the if part and directly call the mail function by passing the arguments to, subject, message and header.
Next two lines print the result of mail function whether mail delivered successfully or not.
Watch the video for demo

If you face any problem in using code to send email using PHP mail function, just ask it on our Ask Question page.