DEV Community 👩‍💻👨‍💻

Cover image for How to send email using PHP?
Rutik Bhoyar
Rutik Bhoyar

Posted on

How to send email using PHP?

Recently I started learning PHP. I was building a practice project where I want to send the email to my email address from the contact us page on my site. Then I wrote the following code.

I know many of the beginners struggle in this part so I am sharing the code so that one can use it with any HTML form they have on their site.

So the steps are:

Step 1: Create a HTML contact form

Step 2: Create the .php file when someone clicks the submit button it will go to the .php file which we defined in the form action.

<?php
//get data from form  
$name = $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];
$to = "youremail@mail.com";
$subject = "Mail From website";
$txt ="Name = ". $name . "\r\n  Email = " . $email . "\r\n Message =" . $message;
$headers = "From: noreply@yoursite.com" . "\r\n" .
"CC: somebodyelse@example.com";
if($email!=NULL){
    mail($to,$subject,$txt,$headers);
}
//redirect
header("Location:thankyou.html");
?>
Enter fullscreen mode Exit fullscreen mode

Hope you will find it helpful.

Top comments (1)

Collapse
 
sinvalfelisberto profile image
Sinval Felisberto

I wiil try it!
Thanks for sharing!

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.