www.ntnu.no *
INFOWEB >  developement and programming >  web development  > How to send an email from a webpage
Tasks
You may add comments
Or e-mail this article
Read articles written by langemyh
User rating
How much did this article help you?
Much Some Little
Print preview
You do not need a 'printer-friendly page' to print this page. Here's why
Contents

How to send an email from a webpage

How to use PHP to send an email from a webpage

If you make an orderingsystem on a webpage, it is often useful to get an email sendt to you containing the information. In this article I will give you a brief introduction to how you can do this.

First of all you need a html-page containing the orderform.

mail.html

kode #1
   			<form method="post" action="mail.php">
    		<textarea name="body"></textarea>
    		<input type="submit" name="submit" value="send"/>
   			</form>
  		

This form vil send all the information to mail.php, which will do the actual sending of the email.

mail.php

kode #2
  			<?php
  				// Configuratoin
  				$to="s.sprett@ntnu.no";
  				$subject="Mail from your webpage";

  				// Send the email
  				if (mail($to, $subject, $_POST['body']))
          {
    				print ( "This mail where sent to $to : \n" .
            	"Subject: $subject \n" .
	    				"Message: $_POST['body']");
  				} 

  				else 
          {
   					print ( "An error occured while sending the email... Go back and try again.\n");
  				}
  			?>
  		

To and Subject-header is written directly into the code. This prevents the user to specify an emailadress and a subject for the email. Remember to do this, because it will limit abuse of the site.

Improvements

There are many improvements to this code. What I am trying to show here, is that it is important to limit the user from abusing the system. Improvements can include more advanced us of the mail() function in PHP, like adding more headers:

kode #3
					mail( $to, $subject, $_POST['body'], 
      			"From: My webform <$username@$SERVER_NAME>\n" .
      			"X-Originating-IP: $REMOTE_ADDR\n");
      	

The variable $username, can typically be replaced by a valid username.

You can also limit the IP-adresses which is allowed to send emails from the form. Examples can be found at php.net.

Convert from FormMail.pl

You have to have a recipient part, which gets the variables from the form, prints them out on a easy-to-understand way and sends it all with the mail()-function. It is recomended to write own scripts for each site. Generic solutions are more easy to abuse.


Languages: en flag_no Comments: 0 Aid: 506 User rating:
 
 
Last updated: 2007-07-17 Author: langemyh Read: 186 times