Sending email through PHP

Intro

Thousands of websites use contact forms to communicate with their users. You will have almost certainly seen one if not used one to contact someone. The contact form will take the users information that he or she has filled in then send the data over to our php script for processing. In our case the data will be sent over to us in an email.


Creating the HTML Feedback Form

Below is the HTML code to create our feedback form.

<form method="post" action="sendmail.php">
Email: < input name="email" type="text" />
Message:
<textarea name="message" rows="10" cols="30">
</textarea>
<input type="submit" />
</form>

The form will take the email address and message from the user and sends the information to sendmail.php via the form, action="sendmail.php".

The php script will know which piece of information being sent by the input name="" tag. So we know the email will be typed in the email box by the name tag: name="email"

The PHP code to sendmail

Now we have set the form to POST the data to sendmail.php we need to create a new file named “sendmail.php". Once you have created the file you can enter the following code into your empty php file. Don’t worry I’ll explain each line in a moment.

<?
$email = $_GET['email'] ;
$message = $_GET['message'] ;
mail( "yourname@example.com", "Email Subject", $message, "From: $email" );
print "Congratulations your email has been sent";
?>

Okay this script will now send email out using php’s sendmail function yeh! Now I’ve got some explaining to do.

Line 2 - 3: These get the data from the form keeping in mind the email form box is named name="email" and the $_GET variable is also called email.

Line 4: This is the clever part that sends the email, The mail() function allows to… specify the email address of the recipient, place the the subject of the email which will appear in the subject line, puts the message of the email which appears in the emails main body and the function allows you to specify the senders email so the recipient can then send a reply if required.

The sendmail function is no way limited to this configuration but as a beginner tutorial this is the minimum information you need to make mail() work.

For more information on the sendmail function then please goto phps sendmail function page.

line 5 - Will display “Congratulations your email has been sent"

I hope the tutorial helps any comments or question as always can be post below.

Dani AI

Generated

Good catches by and : if your form uses method="post", read values with $_POST, not $_GET. And , seeing PHP source in the browser usually means the file was not parsed by PHP. Use full tags <?php ... ?> (not short <?) and make sure the server actually runs PHP.

Here is a safer, more reliable sendmail.php you can drop in. It validates input, prevents header injection, uses your own domain for the From header, and reports success/failure:

<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method not allowed');
}

$email   = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$message = trim($_POST['message'] ?? '');

if (!$email)           exit('Please enter a valid email address.');
if ($message === '')   exit('Please enter a message.');
if (preg_match('/[\r\n]/', $email)) exit('Invalid email header.');

$to      = 'yourname@example.com';          // change to your address
$subject = 'Contact form';
$headers = [
    'From: noreply@example.com',            // use an address on your domain
    "Reply-To: $email",                     // user address goes here
    'MIME-Version: 1.0',
    'Content-Type: text/plain; charset=UTF-8',
];

$sent = mail($to, $subject, $message, implode("\r\n", $headers));
echo $sent ? 'Thanks, your message was sent.' : 'Sorry, sending failed.';

Troubleshooting tips:

  • If the page prints code, PHP is not executing. Confirm .php files are handled by PHP and short tags are disabled or replaced with <?php.
  • If emails arrive blank, confirm your name attributes match what you read in PHP and trim() the message.
  • If mail never arrives, check the mail() return value, server logs, and spam folder. For consistent delivery use SMTP with a library (e.g., PHPMailer or Symfony Mailer) and keep From on your domain, using Reply-To for the user.

Recommended Answers

All 5 Replies

Why does the page you have calling the PHP set up to use POST variables (e.g., form method=post) and the PHP script set up to use GET variables (e.g., $_GET[])? This should not work properly.

commented: The PHP script should use $_POST, not $_GET. Also, even though this is a trivial example, the script should sanitize input before sending the email. +0

I tried this out....and after hitting submit...the sendmail.php page comes up with the code in it? The code for posting was supposed to go into the sendmail.php page right?
Thanks for your help! Greatly appreciate it

i followed this tutorial and ran into an error with the stated sendmail.php code.. when i send information through the feedback form although i recieved an email and the address of my choice i didnt recieve any email content apart from the subject.

after some research i found out you need to use $_post instead of $_get

here is my code for sendmail.php

<?php 
  $email = $_POST['email'] ;
  $message = $_POST['message'] ;
  
  mail ("[EMAIL="imperial@sublime.maantok-ent.com"]imperial@sublime.maantok-ent.com[/EMAIL]", "Feedback form results", $message, "From: $email") ;
  print "Congratulations your email has been sent";
?>

Imperial

Reply:

Two Questions:
1. Your html form says POST
Your php file says GET.
Contradiction?

2. Can I "borrow" the rest of the PHP file and if so where can i see it?
Thanks!


Sending email through PHP

Intro

Thousands of websites use contact forms to communicate with their users. You will have almost certainly seen one if not used one to contact someone. The contact form will take the users information that he or she has filled in then send the data over to our php script for processing. In our case the data will be sent over to us in an email.


Creating the HTML Feedback Form

Below is the HTML code to create our feedback form.

<form method="post" action="sendmail.php">
Email: < input name="email" type="text" />
Message:
<textarea name="message" rows="10" cols="30">
</textarea>
<input type="submit" />
</form>

The form will take the email address and message from the user and sends the information to sendmail.php via the form, action="sendmail.php".

The php script will know which piece of information being sent by the input name="" tag. So we know the email will be typed in the email box by the name tag: name="email"

The PHP code to sendmail

Now we have set the form to POST the data to sendmail.php we need to create a new file named “sendmail.php". Once you have created the file you can enter the following code into your empty php file. Don’t worry I’ll explain each line in a moment.

<?
$email = $_GET['email'] ;
$message = $_GET['message'] ;
mail( "yourname@example.com", "Email Subject", $message, "From: $email" );
print "Congratulations your email has been sent";
?>

Okay this script will now send email out using php’s sendmail function yeh! Now I’ve got some explaining to do.

Line 2 - 3: These get the data from the form keeping in mind the email form box is named name="email" and the $_GET variable is also called email.

Line 4: This is the clever part that sends the email, The mail() function allows to… specify the email address of the recipient, place the the subject of the email which will appear in the subject line, puts the message of the email which appears in the emails main body and the function allows you to specify the senders email so the recipient can then send a reply if required.

The sendmail function is no way limited to this configuration but as a beginner tutorial this is the minimum information you need to make mail() work.

For more information on the sendmail function then please goto phps sendmail function page.

line 5 - Will display “Congratulations your email has been sent"

I hope the tutorial helps any comments or question as always can be post below.

~Removed after reading forum rules~

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.