Sending mail using PHP
by
TDavid, Script
School
Review
Welcome to the ongoing
PHP programming course for PHP. So far we have reviewed strings, arrays
(including manually filling them and determining the size of them), using the
date function to make things happen based on what day it
is, randomization of numbers and events, how to blend PHP with
HTML, and last week we dug into how to make forms and loops. This week we are
going to dive into how to send email using PHP. If you have never done any
programming before and you have just discovered this course tutorial first, you
are encouraged to go back and go through the other five tutorials before
continuing with this course. These tutorials build on concepts and functions
learned in the prior week's tutorials.
Sending email
through a form without using
PHP
To send email through a
form you actually don't even need PHP, but there are several good reasons to
use PHP. Using the form enctype we can directly dump the contents of a form to
email like this:
<form METHOD=POST
ENCTYPE="text/plain" action="mailto:youremail@yourisp.com"> Name:
<input type="text" name="name"> Your Email: <input type="text"
name="email" size=40> URL: <input type="text" name="url">
<input type="submit" value="Submit"></form>
While this is useful for
some, there is a problem in that you can't actually label the contents of the
form, you just get the results. This is where using PHP comes in and
specifically the function called mail().
Using mail() to
send mail in PHP
Let's look at the
function mail() and how to use it. By default your host has configured the
mail() function to use the UNIX sendmail so you don't have to go through the
work of defining the path to sendmail as you do in Perl. This makes sending
mail even easier!
SYNTAX:
mail($recipient, $subject, $body_of_email, $additional_headers);
$recipient = the email
address of the person you are sending to, this can be a variable or direct
assignment using quotes $subject = the subject line of the email, this can
be a variable or direct assignment using quotes $body_of_email = the
contents of the email, this can be a variable or a direct assignment using
quotes $additional_headers = this is typically the "From:
youremail@yourisp.com\n" but it could also be used to send additional headers
like bcc, cc, MIME and more. You separate each header by the new line character
\n.
Let's send a simple
email to me at tdavid@scriptschool.com using php:
<?
if(mail("tdavid@scriptschool.com", "Test subject line TDavid from php course",
"Test body of email", "From: youremail@yourisp.com\n")) {
print('mail successfully sent to TDavid'); } else { print('oops!
something didn't work right above, check the syntax of your code'); }
?>
We demonstrate above how
you can replace the $variable name with direct assignment by quotes in the
example above and use a conditional to let you know that the mail was
successfully sent. If sendmail wasn't configured on your server or the code
syntax is wrong you'll get the error message. It is a good idea to always use a
conditional like this when sending mail so that you can let the person
submitting the form know everything went ok. Now let's do the same thing using
variables instead:
<? $recipient =
'youremail@yourisp.com'; $subject = 'Test email'; $body_of_email =
'This is just a test of the contents of email that we can send and how it
can span multiple lines and boy this is a run-on sentence but I hope you
get the point and I really hope my English teacher does not see
this.'; $additional_headers = 'From: tdavid@scriptschool.com\n'; // don't
forget the new line at the end if(mail($recipient, $subject,
$body_of_email, $additional_headers)) { print("mail successfully
sent to $recipient"); } else { print('oops! something didn't
work right above, check the syntax of your code'); }
Submitting from
a form and building an email to send
Now knowing what we
learned last week in form we can build a form and PHP will turn the names of
the input fields into variables. Let's go back to the original form and use PHP
to submit the form onto itself. We'll use a built-in variable called $PHP_SELF
which will call the form upon itself and add a hidden input tag for a trigger
to actually send the mail.
<? if($action ==
"send_mail") { $recipient =
'youremail@yourisp.com\n'; $subject = "Just a test from
$name"; $body_of_$email = "
This is the contents of the email from Name: $name
Who's email is: $email and who's URL is: $url
"; $additional_headers = "From:
$email\n"; if(mail($recipient, $subject, $body_of_email,
$additional_headers)) { print("mail
successfully sent to $recipient"); } else {
print('oops! something didn't work right
above, check the syntax of your code'); } }
else { ?> <form METHOD=POST action="<? $PHP_SELF
?>"> <input type="hidden" name="action" value="send_mail">
Name: <input type="text" name="name"> Your Email: <input
type="text" name="email" size=40> URL: <input type="text"
name="url"> <input type="submit" value="Submit"></form>
<? } ?>
The first time you call
this script it will spit out the form asking to be submitted, and then when you
hit the submit button your mail should be sent to whatever email address is
listed in $recipient.
Validating the
syntax of email addresses using regular expressions
You probably want to
verify whether the emails you are getting say, for an opt-in newsletter are
valid. To do this you'd first want to make sure the email looks like an email
address. You can do this using a regular expression. Regular expressions are a
way to match patterns and characters. Since we know that an email address has a
fairly universal pattern we can devise a regular expression to test any
user-inputted email address to see if it "looks like" a valid email address.
SYNTAX CASE
SENSITIVE MATCHING: ereg("pattern to match", $string to
compare, $array_of_matches) SYNTAX CASE inSENSITIVE MATCHING: eregi("pattern
to match", $string to compare, $array_of_matches)
The following first
example is the pattern I created to validate emails. There are lots of regular
expressions around and mine is not perfect nor am I saying it is the best, it
is simply one you can use. For our class discussion and to-do assignments you
are welcome to use mine or the alternate one which comes from
PHP
Programming by the Wrox team, a book which I'd recommend adding to your PHP
reference library:
// is the $from
email address in valid format?
if(ereg("([[:alnum:]\.\-]+)(\@[[:alnum:]\.\-]+\.+)", $email)) { it's good }
else { it's bad }
An alternate "email
syntax validation" regular expression from Wrox team:
if(ereg("^(.+)@(.+)\\.(.+)$", $email) { it's good } else { it's
bad }
Right now don't get hung
up on what all those symbols mean, just understand that what this does is check
an email address to see if it is in the correct format. Again, it isn't
perfect, and often regular expressions never are an exact science. So this is
one of those things where if you are close to exact it will have to work. Next
week when we explore regular expressions in depth we'll dissect this regular
expression so that you can understand what all of it means and how to make your
own.
Now let's insert this
email syntax code to check the address before sending the mail.
if(ereg("([[:alnum:]\.\-]+)(\@[[:alnum:]\.\-]+\.+)", $recipient))
{ if(mail($recipient, $subject, $body_of_email,
$additional_headers)) { print("mail
successfully sent to $recipient"); } else {
print('oops! something didn't work right above, check the syntax of your
code'); } } else { print("oops it appears like your
email: $recipient is not in the correct format"); }
SECURITY ALERT: Before sending mail to a
user submitted email address you should always ensure that it
"looks like" a real email address. It is considered very poor programming to
accept input and pass it along to sendmail or to the server or to a file system
without checking to ensure it looks right.
Sending email to
multiple recipients
<rant> Do not
spam! Ok, I have to insert this here because too many people on the net these
days (I'm sure nobody reading this could ever fall into this heinous trap)
abuse what is really a pretty simple concept: Don't send unsolicited mail to a
large body of people </rant> Ok, now that I have that off my chest
...
You can send to multiple
recipients two different ways. You can create a for() loop and cycle through an
array of email addresses (recommended method) or you can simply separate
recipients by commas such as this:
$recipient =
'email1@isp.com, email2@isp.com, email3@isp.com';
I like the first method
using a loop because it can stop the usage of that horribly abused "reply to
all" mail function. If you send out your mail list using the comma method then
everybody and their uncle could reply to your mail list. If you've ever been
part of an email thread that never seems to go away, you know exactly what I'm
talking about here. Here's how to create a simple mail loop using for() and a
list of 4 email addresses:
<? $recipients =
array('email1@yourisp.com', 'email2@yourisp.com', 'email3@yourisp.com',
'email4@yourisp.com'); $sizeof = count($recipients); $subject = 'test
multiple recipients'; $body_of_email = 'blah blah blah';
$additional_headers = "From: youremail@yourisp.com\n"; for($i = 0; $i <
$sizeof; $i++) { if(mail($recipients[$i], $subject,
$body_of_email, $additional_headers)) {
print("<br>mail successfully sent to
$recipient"); } else { print("<br>oops!
something didn't work right above, error on $recipient[$i]"); } }
?>
Now you should have the
knowledge to complete this week's to-do lessons. Good luck!
(basic)
TO-DO ASSIGNMENT: Write a script to accept form input and send the comments to
and from someone that is input via form, do not hardcode the recipient or the
from address. Add in security to make sure that the "to" and "from" look like
legitimate email addresses and use the $PHP_SELF variable. This should all
be one self-contained script with NO include() or require() files.
(advanced) TO-DO ASSIGNMENT: Write a "Share these
urls with your friends" script which will send a series of at least 3 different
urls that the user must enter into the form to at least 3 different email
addresses. Add in security to make sure that the "to" and "from" look like
legitimate email addresses and use the $PHP_SELF variable. This should all
be one self-contained script with NO include() or require()
files.
Need help with your assignment or have
questions about the first week's course?
This concludes our sixth
course on PHP programming. In the next course we'll examine regular expressions
and environment variables.
TDavid is co-owner, programmer and
webmaster for several sites devoted to programming including his own
http://www.tdscripts.com/ He has done custom programming
in various programming languages for companies all over the world. Every Friday
at 2pm PST you can catch his weekly radio show dedicated to the technical side
of webmastering and programming at
http://www.scriptschool.com/radio
Warning: require(/home/adultnetsurprise.com/public_html/multiforum/feedback.php) [function.require]: failed to open stream: No such file or directory in /home/adultnetsurprise.com/public_html/zones/learning/php/php_week_6.html on line 363
Fatal error: require() [function.require]: Failed opening required '/home/adultnetsurprise.com/public_html/multiforum/feedback.php' (include_path='.:/usr/local/lib/php') in /home/adultnetsurprise.com/public_html/zones/learning/php/php_week_6.html on line 363
|