3 # Copyright (C) 2006 Jason Woofenden
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 # This function will SAFELY send e-mail (ie you can pass parameters to it
21 # that you got from a form and not worry about header injection.) Weird
22 # characters are stripped from the $subject and from the real names, but e-mail
23 # addresses are not modified at all.
26 # 0: e-mail successfully accepted for delivery
27 # 1: badly formatted "from" address
28 # 2: badly formatted "to" address
29 # 5: message rejected by mail() (reason unknown)
31 # You cannot pass more than one address to any parameter
32 # address fields (from, to, cc, bcc) can be in either of these formats:
33 # 1) me@foo.com 2) Me Who <me@foo.com>
34 # returns 0 on success
35 function email($from, $to, $subject, $message, $reply_to = '', $cc = '', $bcc = '') {
36 if(($from = email_header($from)) === false) { return 1; }
37 if(($to = email_header($to)) === false) { return 2; }
38 if(($cc = email_header($cc)) === false) { return 3; }
39 if(($bcc = email_header($bcc)) === false) { return 4; }
40 if($from == '') { return 1; }
41 if($to == '') { return 2; }
43 #FIXME should allow many more characters here
44 $subject = ereg_replace("[^a-zA-Z0-9 _'.:-]", '_', $subject);
46 $headers = "From: $from";
48 $headers .= "\r\nReply-To: $reply_to";
51 $headers .= "\r\nCC: $cc";
54 $headers .= "\r\nBCC: $bcc";
56 #header('Content-Type: text/plain');
57 #print_r(array($to, $subject, $message, $headers));
59 if(mail($to, $subject, $message, $headers)) {
68 # This function probably isn't useful appart from writing functions like email() above.
70 # addr can be in these formats:
71 # 1) me@foo.com 2) Me Who <me@foo.com> 3)
72 # returns false, or a valid format 2 above, except if input is an empty string, it'll return an empty string
73 function email_header($addr) {
78 if(ereg('<.*>$', $addr) !== false) {
80 $div = strrpos($addr, '<');
81 $name = substr($addr, 0 , $div);
83 $email = substr($addr, $div + 1, -1);
86 $name = ereg_replace('@.*', '', $addr);
89 if(!valid_email($email)) {
93 #FIXME should allow many more characters here
94 $name = ereg_replace("[^a-zA-Z0-9 _'.-]", '_', $name);
96 return $name . ' <' . $email . '>';
101 # return true if e-mail is formatted like a valid email address
102 function valid_email($email) {
103 return ereg('^[0-9a-zA-Z_~.-]+@[0-9a-zA-Z.-]+\.[a-z]+$', $email) !== false;