PHP and E-mail

Main | Review of Operators | Mathematical Functions | Practice 5 | Solution 5 | HTML Forms | PHP Forms | Practice 6 | Solution 6 | PHP and E-mail | Practice 7 | Solution 7

PHP has a very useful built-in function called mail(), which sends email. This function takes several arguments and the easiest way to understand it is to look at an example of it in use.

mail($receiver, $subject, $message, "From: $sender");    

  1. The first argument of the above call to mail() is the variable $receiver. This variable denotes the email address that will receive the email that mail() will send. If you wanted your PHP program to send you mail, you would put your address in the place of $receiver.

  2. The second argument of the above call to mail() is the variable $subject. This variable denotes the subject of email that will be sent by mail().

  3. The third argument of the above call to mail() is the variable $message. This variable denotes the actual message contained within the email that mail() will send. If this variable were echoed, it is possible that you would see many paragraphs, but the first sentence would start with a " and the last sentence would end with a ". This allows PHP to represent the content of a long email with just one variable.

  4. The final argument of the above call to mail() is the string "From: $sender". The 'From: ' is part of a header that email software will parse. The variable $sender denotes who sent the email. This lets the $receiver know who to reply to.

PHP's mail() function can also return a variable that can be true or false, with regard to whether the mail was sent. This can be a useful feature which you can use to echo information to your user, as to the status of their email. The following shows how one could take advantage of this feature:

$sent = mail($receiver, $subject, $message, "From: $sender");
if ($sent) { 
        echo "your message was sent";
}
else {
        echo "your message was not sent"; 
}

In the above $sent will only be true if the mail was sent. If the value of $sent is true the program will tell the user that the mail has been sent. The else statement covers the case where the value of $sent is false, and tells the user that the mail was not sent.

It should now be possible for you to write a web-based email application, that uses HTML's ability to get text from users (as illustrated by Practice 5), and PHP's mail() function. You could also use these tools to create online forms, which would allow you to collect information from users, that could then be e-mailed to whomever you wish.


jfulton [at] member.fsf.org
22 Aug 2013