3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
9 # This function will SAFELY send e-mail (ie you can pass parameters to it
10 # that you got from a form and not worry about header injection.) Weird
11 # characters are stripped from the $subject and from the real names, but e-mail
12 # addresses are not modified at all.
15 # 0: e-mail successfully accepted for delivery
16 # 1: badly formatted "from" address
17 # 2: badly formatted "to" address
18 # 5: message rejected by mail() (reason unknown)
20 # You cannot pass more than one address to any parameter
21 # address fields (from, to, cc, bcc) can be in either of these formats:
22 # 1) me@foo.com 2) Me Who <me@foo.com>
23 # returns 0 on success
24 function email($from, $to, $subject, $message, $reply_to = '', $cc = '', $bcc = '') {
25 if(($from = email_header($from)) === false) { return 1; }
26 if(($to = email_header($to)) === false) { return 2; }
27 if(($cc = email_header($cc)) === false) { return 3; }
28 if(($bcc = email_header($bcc)) === false) { return 4; }
29 if($from == '') { return 1; }
30 if($to == '') { return 2; }
32 #FIXME should allow many more characters here
33 $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);
35 $headers = "From: $from";
37 $headers .= "\r\nReply-To: $reply_to";
40 $headers .= "\r\nCC: $cc";
43 $headers .= "\r\nBCC: $bcc";
45 $headers .= "\r\nContent-type: text/plain; charset=UTF-8";
47 if(mail($to, $subject, $message, $headers)) {
56 # This function probably isn't useful appart from writing functions like email() above.
58 # addr can be in these formats:
59 # 1) me@foo.com 2) Me Who <me@foo.com> 3)
60 # returns false, or a valid format 2 above, except if input is an empty string, it'll return an empty string
61 function email_header($addr) {
66 if(preg_match('|<.*>$|', $addr) === 1) {
68 $div = strrpos($addr, '<');
69 $name = substr($addr, 0 , $div);
71 $email = substr($addr, $div + 1, -1);
74 $name = preg_replace('|@.*|', '', $addr);
77 if(!valid_email($email)) {
81 #FIXME should allow many more characters here
82 $name = preg_replace("|[^a-z0-9 _/'.-]|i", '_', $name);
84 return $name . ' <' . $email . '>';
89 # return true if e-mail is formatted like a valid email address
90 function valid_email($email) {
91 return preg_match('|^[0-9a-zA-Z_~.+-]+@[0-9a-zA-Z.-]+\.[a-z]+$|', $email) === 1;