3 # Copyright (C) 2006 Jason Woofenden
5 # This file is part of wfpl.
7 # wfpl is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2, or (at your option)
12 # wfpl is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with wfpl; see the file COPYING. If not, write to the
19 # Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
24 # This function will SAFELY send e-mail (ie you can pass parameters to it
25 # that you got from a form and not worry about header injection.) Weird
26 # characters are stripped from the $subject and from the real names, but e-mail
27 # addresses are not modified at all.
30 # 0: e-mail successfully accepted for delivery
31 # 1: badly formatted "from" address
32 # 2: badly formatted "to" address
33 # 5: message rejected by mail() (reason unknown)
35 # You cannot pass more than one address to any parameter
36 # address fields (from, to, cc, bcc) can be in either of these formats:
37 # 1) me@foo.com 2) Me Who <me@foo.com>
38 # returns 0 on success
39 function email($from, $to, $subject, $message, $cc = '', $bcc = '') {
40 if(($from = email_header($from)) === false) { return 1; }
41 if(($to = email_header($to)) === false) { return 2; }
42 if(($cc = email_header($cc)) === false) { return 3; }
43 if(($bcc = email_header($bcc)) === false) { return 4; }
44 if($from == '') { return 1; }
45 if($to == '') { return 2; }
47 #FIXME should allow many more characters here
48 $subject = ereg_replace("[^a-zA-Z _'.-]", '_', $subject);
50 $headers = "From: $from";
52 $headers .= "\r\nCC: $cc";
55 $headers .= "\r\nBCC: $bcc";
57 if(mail($to, $subject, $message, $headers)) {
66 # This function probably isn't useful appart from writing functions like email() above.
68 # addr can be in these formats:
69 # 1) me@foo.com 2) Me Who <me@foo.com> 3)
70 # returns false, or a valid format 2 above, except if input is an empty string, it'll return an empty string
71 function email_header($addr) {
76 if(ereg('<.*>$', $addr) !== false) {
78 list($name, $email) = split('<', $addr);
80 $email = substr($email, 0, -1); # get rid of the '>' at the end
83 $name = ereg_replace('@.*', '', $addr);
86 if(!valid_email($email)) {
90 #FIXME should allow many more characters here
91 $name = ereg_replace("[^a-zA-Z _'-]", '_', $name);
93 return $name . ' <' . $email . '>';
98 # return true if e-mail is formatted like a valid email address
99 function valid_email($email) {
100 return ereg('^[0-9a-zA-Z_~.-]+@[0-9a-zA-Z.-]+\.[a-z]+$', $email) !== false;