hee

Search Here

Custom Search

Recent Posts



Archives

Categories

Subscribe to Feeds


feed subscription feed subscription

Enter your email address:

Delivered by FeedBurner

How To Send Email Using PHP

on May 06in PHP, Tutorials tagged ,

One of the most important script of a website is its ability for its visitors to send an email inquiry to the administrators. In this tutorial, I will outline a way on how to send email from your website using php.

The steps that we are going to take are the following:

1. Validate if the email entered is a real email.
2. Make sure that there are no strings that are included for manipulation.
3. Send the email using php.
4. Redirect back the user to a thank you page.

Note that originally I wanted to include the form part in passing the data from the User Forms but I decided that I wanted to focus more on the email script.

A. Get the data and pass it on to your variables.

$to = test@yahoo.com;
$from = sender@yahoo.com;
$subject = "This is test from my website";
$body = "Include a message here";

$headers = "From: $email";

mail($to, $subject,$body, $headers);

header("Location: thanks.php");

The above script will already let you send an email, however we wanted to include some simple security settings.

B. Check if the email is valid

function is_valid_email($email) {

  return preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s]+\.+[a-z]{2,6}))$#si', $email);

}

if (!is_valid_email($email)) {

  header("Location: index.php?flg=Invalid email submitted - mail not being sent.");

  exit;

}

C. Check for bad strings

function contains_bad_str($str_to_test) {

  $bad_strings = array(
                "content-type:"
                ,"mime-version:"
                ,"multipart/mixed"
		,"Content-Transfer-Encoding:"
                ,"bcc:"
		,"cc:"
		,"to:" );

  foreach($bad_strings as $bad_string) {
    if(eregi($bad_string, strtolower($str_to_test))) {
      header("Location: index.php?flg=Suspected injection attempt - mail not being sent.");
      exit;

    }

  }

}

D. Include this before the mail function. This will check for script B and C.


contains_bad_str($email);
contains_bad_str($subject);
contains_bad_str($body);

That’s it, you can now send an email from your website using the script above. By the way, the mail() function of php is using the SMTP of your hosting server. Make sure that the SMTP of your hosting provider is properly configured.

Bookmark and Share

Share this Post.



There are no comments yet, add one below.

Leave a Comment