Lesson 14: Sending E-Mail - TOP10

Lesson 14: Sending E-Mail

Using PHP to send the contents of a form to a specified e-mail address is so easy that you’ll wonder why more people don’t do it every day.

Using an SMTP Server

SMTP is an acronym for Simple Mail Transfer Protocol, and an SMTP server is a machine that transports mail, just like a Web server is a machine that displays Web pages when requested. An SMTP server is sometimes referred to as an outgoing mail server, which brings me to the point—you need one in order to complete the exercises in this chapter. On Linux/UNIX, Sendmail and Qmail are popular packages. On Windows, the SMTP service in the Windows NT Service Pack, or the service built into the Windows 2000 operating system, is often used.

However, if you have installed Apache, PHP, and MySQL as part of a development environment on your personal machine, you probably do not have SMTP running locally. If that’s the case, you can access an outgoing mail server that might already be available to you.

EXPECTED INSTALLS If you skipped the first three chapters of this book and are using PHP as part of an Internet service provider’s virtual hosting package, the SMTP server should already be installed on that machine, and PHP should be properly configured to access it.

If your machine is connected to the Internet via a dial-up connection, DSL, cable, or other type of access, you can use your Internet service provider’s outgoing mail server. For example, if your development machine is a Windows box with a DSL connection to the Internet, you can use something like mail.yourprovider.com as your outgoing mail server. The rule of thumb is that whatever you have configured within your e-mail client (Eudora, Outlook, Netscape Mail, and so on) as your outgoing mail server will also function within your PHP code as your SMTP server. The trick is making PHP aware of this little fact, which you’ll learn about next.

SMTP-Related Changes in php.ini 

In the php.ini master configuration file, there are a few directives that need to be set up so that the mail() function works properly. Open php.ini with a text editor and look for these lines:

[mail function] ; For Win32 only. SMTP = localhost ; For Win32 only. sendmail_from = me@localhost.com ; For Unix only. You may supply arguments as well (default: 'sendmail -t -i'). ;sendmail_path =

If you are using Windows, you’ll need to modify the first two directives, SMTP and sendmail_from. If you plan to use the outgoing mail server of your ISP (in this example, suppose it’s called DSLProvider.net), the entry in php.ini would look like this: SMTP = mail.dslprovider.net The second configuration directive is sendmail_from, and this is the e-mail address used in the From header of the outgoing e-mail. It can be overwritten in the mail script itself but normally operates as the default value. For example:

sendmail_from = youraddress@yourdomain.com
Of course, replace youraddress@yourdomain.com with your own address.
If you’re on Linux or a UNIX variant, sendmail_path is all you need to worry about, and it should look something like this:
 sendmail_path = /usr/sbin/sendmail
Or, if you’re using Qmail:
 sendmail_path = /var/qmail/bin/sendmail
In the sendmail_path directive, you can also set configuration flags to specify queuing options or to explicitly set the Return-Path header, such as:
 sendmail_path = /usr/sbin/sendmail -t -fyou@yourdomain.com
After making changes to the php.ini file, restart the Web server and use the phpinfo() function to verify that the changes have been made. When that’s done, you’re ready to send some e-mail using PHP.

PHP mail() function 

The PHP mail() function is used to send emails from inside a script. Syntax:  mail(to,subject,message,headers,parameters)



Example1:  In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail:  <?php $to = "someone@example.com"; $subject = "Test mail"; $message = "Hello! This is a simple email message."; $from = "someonelse@example.com"; $headers = "From:" . $from; mail($to,$subject,$message,$headers); echo "Mail Sent."; ?>
Example2: The example below sends a text message to a specified e-mail address:
 <html> <body>
<?php if (isset($_REQUEST['email'])) //if "email" is filled out, send email   {   //send email   $email = $_REQUEST['email'] ;   $subject = $_REQUEST['subject'] ;   $message = $_REQUEST['message'] ;   mail("someone@example.com", "$subject",   $message, "From:" . $email);   echo "Thank you for using our mail form";   } else //if "email" is not filled out, display the form   {   echo "<form method='post' action='mailform.php'>   Email: <input name='email' type='text' /><br />   Subject: <input name='subject' type='text' /><br />   Message:<br />   <textarea name='message' rows='15' cols='40'>   </textarea><br />   <input type='submit' />   </form>";   } ?>
</body> </html>
This is how the example above works:  First, check if the email input field is filled out

 If it is not set (like when the page is first visited); output the HTML form  If it is set (after the form is filled out); send the email from the form  When submit is pressed after the form is filled out, the page reloads, sees that the email input is set, and sends the email   Note: This is the simplest way to send e-mail, but it is not secure. In the following of this tutorial you can read more about vulnerabilities in e-mail scripts, and how to validate user input to make it more secure.
The problem with the code above is that unauthorized users can insert data into the mail headers via the input form.
What happens if the user adds the following text to the email input field in the form?
 someone@example.com%0ACc:person2@example.com %0ABcc:person3@example.com,person3@example.com, anotherperson4@example.com,person5@example.com %0ABTo:person6@example.com
The mail() function puts the text above into the mail headers as usual, and now the header has an extra Cc:, Bcc:, and To: field. When the user clicks the submit button, the e-mail will be sent to all of the addresses above!
PHP Stopping E-mail Injections The best way to stop e-mail injections is to validate the input.
The code below is the same as in the previous chapter, but now we have added an input validator that checks the email field in the form:
 <html> <body> <?php function spamcheck($field)   {   //filter_var() sanitizes the e-mail   //address using FILTER_SANITIZE_EMAIL   $field=filter_var($field, FILTER_SANITIZE_EMAIL);
  //filter_var() validates the e-mail   //address using FILTER_VALIDATE_EMAIL   if(filter_var($field, FILTER_VALIDATE_EMAIL))     {     return TRUE;     }   else     {     return FALSE;     }   }
if (isset($_REQUEST['email']))   {//if "email" is filled out, proceed

  //check if the email address is invalid   $mailcheck = spamcheck($_REQUEST['email']);   if ($mailcheck==FALSE)     {     echo "Invalid input";     }   else     {//send email     $email = $_REQUEST['email'] ;     $subject = $_REQUEST['subject'] ;     $message = $_REQUEST['message'] ;     mail("someone@example.com", "Subject: $subject",     $message, "From: $email" );     echo "Thank you for using our mail form";     }   } else   {//if "email" is not filled out, display the form   echo "<form method='post' action='mailform.php'>   Email: <input name='email' type='text' /><br />   Subject: <input name='subject' type='text' /><br />   Message:<br />   <textarea name='message' rows='15' cols='40'>   </textarea><br />   <input type='submit' />   </form>";   } ?>
</body> </html> In the code above we use PHP filters to validate input:  The FILTER_SANITIZE_EMAIL filter removes all illegal e-mail characters from a string  The FILTER_VALIDATE_EMAIL filter validates value as an e-mail address
Send an HTML email <?php $to = "somebody@example.com, somebodyelse@example.com"; $subject = "HTML email";
$message = " <html> <head> <title>HTML email</title> </head> <body> <p>This email contains HTML Tags!</p> <table> <tr> <th>Firstname</th>

<th>Lastname</th> </tr> <tr> <td>John</td> <td>Doe</td> </tr> </table> </body> </html> ";
// Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers $headers .= 'From: <webmaster@example.com>' . "\r\n"; $headers .= 'Cc: myboss@example.com' . "\r\n";
mail($to,$subject,$message,$headers); ?>  
Previous
Next Post »