class.email.php

By: arvin
December 22, 2009

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php
 
// $email =& Email::fromStream();
 
require_once dirname(dirname(__FILE__)).'/3rd-party/mail/mimeDecode.php';
 
class EmailResource {
 
    var $headers;
    var $body;
    var $parts;
    var $ctype_primary;
    var $ctype_secondary;
    var $ctype_parameters;
    var $content_disposition;
    var $d_parameters;
 
    function EmailResource() {
        $this->headers = array();
        $this->body    = '';
        $this->parts   = array();   
    }
}
 
 
class Email {
 
    var $raw;
    var $resource;
    var $log = array();
 
    function Email($input='') {
        if($input) {
 
            $this->raw = $input;
            $this->log('loading mimeDecode library');
 
            $params['include_bodies'] = true;
            $params['decode_bodies'] = true;
            $params['decode_headers'] = true;
            $params['input'] = $input;
 
            $this->log('Decoding stream for mime message');
            $this->resource = Mail_mimeDecode::decode($params);
 
        } else {
            $this->resource = new EmailResource();
            $this->log('New mime message created!');
        }
    }
 
    function log($msg = null) {
        if(is_bool($msg)) {
            $htmlOn = $msg;
            $msg = null;
        }
        if($msg !== null)
            $this->log[]="$msg";
 
        $output = implode("\n", $this->log);
        if($htmlOn)
            return nl2br($output);
        else
            return $output;
    }
 
    function addHeader($key, $value) {
        $this->log("Add header[$key: $value]");
        $this->resource->headers[$key] = $value;
    }
 
    function headers() {
        $str = '';
        foreach($this->resource->headers as $key => $value)
            $str .= "$key: $value\r\n";
        $this->log("Output headers [$str]");
        return $str;
    }
 
    function header($key) {
        $this->log("Get header [$key: ".$this->resource->headers[$key]."]");
        return $this->resource->headers[$key];
    }
 
    function body($data = null) {
        if($data === null) {
            return $this->resource->body;
 
        } else {
            $this->resource->body = $data;
        }
    }
 
    function part($primaryType, $secondaryType = null, $body = null) {
        if($secondaryType === null) {
            $this->log("Explode [$primaryType]");
            list($primaryType, $secondaryType) = explode('/', $primaryType);
        }
 
        if($body !== null) {
            // TODO build a multipart email
            $this->log("Add a new part");
 
        } else {
 
            $this->log("Looking for Content-Type: $primaryType/$secondaryType");
            $resource = array();
            list($type,) = $this->contentType(true);
            if($type == 'multipart') {
                $this->log("Email has multiple parts");
                $resource = $this->resource->parts;
            } else {
                $this->log("Email is not multipart");
                $resource = array($this->resource);
            }
 
            $parts = array();
            $this->log("Iterate through the parts");
            foreach ($resource as $part) {
                $this->log("Found part with Content-Type: ". $this->contentType($part));
                $this->log("Is [".$this->contentType($part)."] == [$primaryType/$secondaryType]?");
                if (0 == strcmp($this->contentType($part), "$primaryType/$secondaryType")) {
                    $this->log("Found a matching part.");
                    $parts[] = $part;
                    $this->log("Add to results array [".count($parts)."]");
                }
            }
            $this->log("Return the list of found parts");
            return $parts;
        }
    }
 
    function contentType($resource = null, $primary = null, $secondary = null) {
        if($resource === null)
            $resource = $this->resource;
 
        if(is_bool($resource)) {
            $primary  = $resource;
            $resource = $this->resource;
        }
 
        if((is_bool($primary) || $primary === null) && $secondary === null) {
            $this->log("Fetching Content-Type of part");
            $type = array($resource->ctype_primary, $resource->ctype_secondary);
            if($primary === true) {
                $this->log("Return array(". implode(',', $type) .")");
                return $type;
            } else {
                $this->log("Return ${type[0]}/${type[1]}");
                return $type[0].'/'.$type[1];
            }
        }
    }
 
    function text($body = null) {
        if($body !== null) {
            $this->log("Create a new text body");
            return $this->part('text', 'plain', $body);
 
        } else {            
 
            $this->log("Look for part with Content-Type: text/plain");
            $text = $this->part('text/plain');
            if(count($text) > 0) {
                // TODO handle multiple parts of the same type
                $this->log("Returning ".$text[0]->body);
                return $this->removeSignature($text[0]->body);
 
            // look for text/html second
            } 
 
            $this->log("No matching parts found");
            $this->log("Look for part with Content-Type: text/html");
            $text = $this->part('text/html');
            if(count($text) > 0) {
                // TODO handle multiple parts of the same type
 
                $body = $text[0]->body;
                $body = strip_tags($body);
                $this->log("Tags are stripped");
                $body = html_entity_decode($body);
                $this->log("Converted to ASCII");
 
                $this->log("Returning $body");
                return $body;
            }            
 
            $this->log("No matching parts found");
            $this->log("Giving up on looking for parts with Content-Type: text/*");
            return 'No text found.';
        }
    }
 
    function removeSignature($text) {        
        // Remove Signature delimited by --
        $sig = (strrpos($text, "\r\n--\r\n") !== false) ? strrpos($text, "\r\n--\r\n"): (strrpos($text, "\n--\n")) ? strrpos($text, "\n--\n"): strrpos($text, "--");
        if($sig !== false) {
            $text = substr($text, 0, $sig);
        }
 
        // Remove original messages/past conversations/RE:
        $sig = strripos($text, 'original message');
        if($sig !== false) {
            $text = substr($text, 0, $sig);
        }        
 
        // Remove Sent from my blah blah
        $sig = strripos($text, 'sent from my');
        if($sig !== false) {
            $text = substr($text, 0, $sig);
        }   
 
        return trim($text);
    }
 
    function subject($data = null) {
        if($data === null) {
            return $this->resource->headers['subject'];            
        } else {
            $this->resource->headers['subject'] = $data;
        }
    }
 
    function from($data = null) {
        if($data === null) {
            return $this->resource->headers['from'];            
        } else {
            $this->resource->headers['from'] = $data;
        }
    }
 
    function fromEmail() {
        $from = $this->from();
        if(strpos($from, '<') !== false) {
            $from = substr($from, strpos($from, '<') + 1);
            $from = substr($from, 0, strpos($from, '>'));
        }
        return $from;
    }
 
    function fromStream($input = 'php://stdin') {
        $data = file_get_contents($input);
        return new Email($data);
    }
 
    function forwardTo($to) {
        $this->log("Forwarding email to $to");
        mail($to, $this->subject(), $this->body(), $this->headers());
    }
}
?>

  • Twitter
  • Facebook
  • email
  • Blogplay
  • Suggest to Techmeme via Twitter
  • Mixx
  • SphereIt
  • Sphinn
  • Tumblr
  • Google Bookmarks
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
About the Author

arvin is an overdue college crammer, occasional programmer, ever-newbie mashup coder, romantic long-distance lover, retired blogger, and ex-puppy-love-fiction writer. http://twitter.com/rvn

Comments RSS | Give a Comment | Trackback

No Comments

Leave a Reply