forked from SSilence/php-imap-client
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Imap.php
693 lines (591 loc) · 19.2 KB
/
Imap.php
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
<?php
/**
* Helper class for imap access
*
* @package protocols
* @copyright Copyright (c) Tobias Zeising (http://www.aditu.de)
* @license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
* @author Tobias Zeising <tobias.zeising@aditu.de>
*/
class Imap {
/**
* imap connection
*/
private $imap = false;
/**
* mailbox url string
*/
private $mailbox = "";
/**
* currentfolder
*/
private $folder = "Inbox";
/**
* initialize imap helper
*
* @return void
* @param $mailbox imap_open string
* @param $username
* @param $password
* @param $encryption ssl or tls
*/
public function __construct($mailbox, $username, $password, $encryption = false) {
$enc = '';
if($encryption!=null && isset($encryption) && $encryption=='ssl')
$enc = '/imap/ssl';
else if($encryption!=null && isset($encryption) && $encryption=='tls')
$enc = '/imap/tls';
$this->mailbox = "{" . $mailbox . $enc . "}";
$this->imap = @imap_open($this->mailbox, $username, $password);
}
/**
* close connection
*/
function __destruct() {
if($this->imap!==false)
imap_close($this->imap);
}
/**
* returns true after successfull connection
*
* @return bool true on success
*/
public function isConnected() {
return $this->imap !== false;
}
/**
* returns last imap error
*
* @return string error message
*/
public function getError() {
return imap_last_error();
}
/**
* select given folder
*
* @return bool successfull opened folder
* @param $folder name
*/
public function selectFolder($folder) {
$result = imap_reopen($this->imap, $this->mailbox . $folder);
if($result === true)
$this->folder = $folder;
return $result;
}
/**
* returns all available folders
*
* @return array with foldernames
*/
public function getFolders() {
$folders = imap_list($this->imap, $this->mailbox, "*");
return str_replace($this->mailbox, "", $folders);
}
/**
* returns the number of messages in the current folder
*
* @return int message count
*/
public function countMessages() {
return imap_num_msg($this->imap);
}
/**
* returns the number of unread messages in the current folder
*
* @return int message count
*/
public function countUnreadMessages() {
$result = imap_search($this->imap, 'UNSEEN');
if($result===false)
return false;
return count($result);
}
/**
* returns unseen emails in the current folder
*
* @return array messages
* @param $withbody without body
*/
public function getUnreadMessages($withbody=true){
$result = imap_search($this->imap, 'UNSEEN');
foreach($result as $k=>$i){
$emails[]= $this->formatMessage($i, $withbody);
}
return $emails;
}
/**
* returns all emails in the current folder
*
* @return array messages
* @param $withbody without body
*/
public function getMessages($withbody = true) {
$count = $this->countMessages();
$emails = array();
for($i=1;$i<=$count;$i++) {
$emails[]= $this->formatMessage($i, $withbody);
}
// sort emails descending by date
// usort($emails, function($a, $b) {
// try {
// $datea = new \DateTime($a['date']);
// $dateb = new \DateTime($b['date']);
// } catch(\Exception $e) {
// return 0;
// }
// if ($datea == $dateb)
// return 0;
// return $datea < $dateb ? 1 : -1;
// });
return $emails;
}
/**
* @param $id
* @param bool $withbody
* @return array
*/
protected function formatMessage($id, $withbody=true){
$header = imap_headerinfo($this->imap, $id);
// fetch unique uid
$uid = imap_uid($this->imap, $id);
// get email data
if ( isset($header->subject) && strlen($header->subject) > 0 ) {
$subject = imap_mime_header_decode($header->subject);
$subject = $subject[0]->text;
} else {
$subject = '';
}
$subject = $this->convertToUtf8($subject);
$email = array(
'to' => isset($header->to) ? $this->arrayToAddress($header->to) : '',
'from' => $this->toAddress($header->from[0]),
'date' => $header->date,
'subject' => $subject,
'uid' => $uid,
'unread' => strlen(trim($header->Unseen))>0,
'answered' => strlen(trim($header->Answered))>0
);
if(isset($header->cc))
$email['cc'] = $this->arrayToAddress($header->cc);
// get email body
if($withbody===true) {
$body = $this->getBody($uid);
$email['body'] = $body['body'];
$email['html'] = $body['html'];
}
// get attachments
$mailStruct = imap_fetchstructure($this->imap, $id);
$attachments = $this->attachments2name($this->getAttachments($this->imap, $id, $mailStruct, ""));
if(count($attachments)>0)
$email['attachments'] = $attachments;
return $email;
}
/**
* delete given message
*
* @return bool success or not
* @param $id of the message
*/
public function deleteMessage($id) {
return $this->deleteMessages(array($id));
}
/**
* delete messages
*
* @return bool success or not
* @param $ids array of ids
*/
public function deleteMessages($ids) {
if( imap_mail_move($this->imap, implode(",", $ids), $this->getTrash(), CP_UID) == false)
return false;
return imap_expunge($this->imap);
}
/**
* move given message in new folder
*
* @return bool success or not
* @param $id of the message
* @param $target new folder
*/
public function moveMessage($id, $target) {
return $this->moveMessages(array($id), $target);
}
/**
* move given message in new folder
*
* @return bool success or not
* @param $ids array of message ids
* @param $target new folder
*/
public function moveMessages($ids, $target) {
if(imap_mail_move($this->imap, implode(",", $ids), $target, CP_UID)===false)
return false;
return imap_expunge($this->imap);
}
/**
* mark message as read
*
* @return bool success or not
* @param $id of the message
* @param $seen true = message is read, false = message is unread
*/
public function setUnseenMessage($id, $seen = true) {
$header = $this->getMessageHeader($id);
if($header==false)
return false;
$flags = "";
$flags .= (strlen(trim($header->Answered))>0 ? "\\Answered " : '');
$flags .= (strlen(trim($header->Flagged))>0 ? "\\Flagged " : '');
$flags .= (strlen(trim($header->Deleted))>0 ? "\\Deleted " : '');
$flags .= (strlen(trim($header->Draft))>0 ? "\\Draft " : '');
$flags .= (($seen == true) ? '\\Seen ' : ' ');
echo "\n<br />".$id.": ".$flags;
imap_clearflag_full($this->imap, $id, '\\Seen', ST_UID);
return imap_setflag_full($this->imap, $id, trim($flags), ST_UID);
}
/**
* return content of messages attachment
*
* @return binary attachment
* @param $id of the message
* @param $index of the attachment (default: first attachment)
*/
public function getAttachment($id, $index = 0) {
// find message
$attachments = false;
$messageIndex = imap_msgno($this->imap, $id);
$header = imap_headerinfo($this->imap, $messageIndex);
$mailStruct = imap_fetchstructure($this->imap, $messageIndex);
$attachments = $this->getAttachments($this->imap, $messageIndex, $mailStruct, "");
if($attachments==false)
return false;
// find attachment
if($index > count($attachments))
return false;
$attachment = $attachments[$index];
// get attachment body
$partStruct = imap_bodystruct($this->imap, imap_msgno($this->imap, $id), $attachment['partNum']);
$filename = $partStruct->dparameters[0]->value;
$message = imap_fetchbody($this->imap, $id, $attachment['partNum'], FT_UID);
switch ($attachment['enc']) {
case 0:
case 1:
$message = imap_8bit($message);
break;
case 2:
$message = imap_binary($message);
break;
case 3:
$message = imap_base64($message);
break;
case 4:
$message = quoted_printable_decode($message);
break;
}
return array(
"name" => $attachment['name'],
"size" => $attachment['size'],
"content" => $message);
}
/**
* add new folder
*
* @return bool success or not
* @param $name of the folder
*/
public function addFolder($name) {
return imap_createmailbox($this->imap , $this->mailbox . $name);
}
/**
* remove folder
*
* @return bool success or not
* @param $name of the folder
*/
public function removeFolder($name) {
return imap_deletemailbox($this->imap, $this->mailbox . $name);
}
/**
* rename folder
*
* @return bool success or not
* @param $name of the folder
* @param $newname of the folder
*/
public function renameFolder($name, $newname) {
return imap_renamemailbox($this->imap, $this->mailbox . $name, $this->mailbox . $newname);
}
/**
* clean folder content of selected folder
*
* @return bool success or not
*/
public function purge() {
// delete trash and spam
if($this->folder==$this->getTrash() || strtolower($this->folder)=="spam") {
if(imap_delete($this->imap,'1:*')===false) {
return false;
}
return imap_expunge($this->imap);
// move others to trash
} else {
if( imap_mail_move($this->imap,'1:*', $this->getTrash()) == false)
return false;
return imap_expunge($this->imap);
}
}
/**
* returns all email addresses
*
* @return array with all email addresses or false on error
*/
public function getAllEmailAddresses() {
$saveCurrentFolder = $this->folder;
$emails = array();
foreach($this->getFolders() as $folder) {
$this->selectFolder($folder);
foreach($this->getMessages(false) as $message) {
$emails[] = $message['from'];
$emails = array_merge($emails, $message['to']);
if(isset($message['cc']))
$emails = array_merge($emails, $message['cc']);
}
}
$this->selectFolder($saveCurrentFolder);
return array_unique($emails);
}
/**
* save email in sent
*
* @return void
* @param $header
* @param $body
*/
public function saveMessageInSent($header, $body) {
return imap_append($this->imap, $this->mailbox . $this->getSent(), $header . "\r\n" . $body . "\r\n", "\\Seen");
}
// private helpers
/**
* get trash folder name or create new trash folder
*
* @return trash folder name
*/
private function getTrash() {
foreach($this->getFolders() as $folder) {
if(strtolower($folder)==="trash" || strtolower($folder)==="papierkorb")
return $folder;
}
// no trash folder found? create one
$this->addFolder('Trash');
return 'Trash';
}
/**
* get sent folder name or create new sent folder
*
* @return sent folder name
*/
private function getSent() {
foreach($this->getFolders() as $folder) {
if(strtolower($folder)==="sent" || strtolower($folder)==="gesendet")
return $folder;
}
// no sent folder found? create one
$this->addFolder('Sent');
return 'Sent';
}
/**
* fetch message by id
*
* @return header
* @param $id of the message
*/
private function getMessageHeader($id) {
$count = $this->countMessages();
for($i=1;$i<=$count;$i++) {
$uid = imap_uid($this->imap, $i);
if($uid==$id) {
$header = imap_headerinfo($this->imap, $i);
return $header;
}
}
return false;
}
/**
* convert attachment in array(name => ..., size => ...).
*
* @return array
* @param $attachments with name and size
*/
private function attachments2name($attachments) {
$names = array();
foreach($attachments as $attachment) {
$names[] = array(
'name' => $attachment['name'],
'size' => $attachment['size']
);
}
return $names;
}
/**
* convert imap given address in string
*
* @return string in format "Name <email@bla.de>"
* @param $headerinfos the infos given by imap
*/
private function toAddress($headerinfos) {
$email = "";
$name = "";
if(isset($headerinfos->mailbox) && isset($headerinfos->host)) {
$email = $headerinfos->mailbox . "@" . $headerinfos->host;
}
if(!empty($headerinfos->personal)) {
$name = imap_mime_header_decode($headerinfos->personal);
$name = $name[0]->text;
} else {
$name = $email;
}
$name = $this->convertToUtf8($name);
return $name . " <" . $email . ">";
}
/**
* converts imap given array of addresses in strings
*
* @return array with strings (e.g. ["Name <email@bla.de>", "Name2 <email2@bla.de>"]
* @param $addresses imap given addresses as array
*/
private function arrayToAddress($addresses) {
$addressesAsString = array();
foreach($addresses as $address) {
$addressesAsString[] = $this->toAddress($address);
}
return $addressesAsString;
}
/**
* returns body of the email. First search for html version of the email, then the plain part.
*
* @return string email body
* @param $uid message id
*/
private function getBody($uid) {
$body = $this->get_part($this->imap, $uid, "TEXT/HTML");
$html = true;
// if HTML body is empty, try getting text body
if ($body == "") {
$body = $this->get_part($this->imap, $uid, "TEXT/PLAIN");
$html = false;
}
$body = $this->convertToUtf8($body);
return array( 'body' => $body, 'html' => $html);
}
/**
* convert to utf8 if necessary.
*
* @return true or false
* @param $string utf8 encoded string
*/
function convertToUtf8($str) {
if(mb_detect_encoding($str, "UTF-8, ISO-8859-1, GBK")!="UTF-8")
$str = utf8_encode($str);
$str = iconv('UTF-8', 'UTF-8//IGNORE', $str);
return $str;
}
/**
* returns a part with a given mimetype
* taken from http://www.sitepoint.com/exploring-phps-imap-library-2/
*
* @return string email body
* @param $imap imap stream
* @param $uid message id
* @param $mimetype
*/
private function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
if (!$structure) {
$structure = imap_fetchstructure($imap, $uid, FT_UID);
}
if ($structure) {
if ($mimetype == $this->get_mime_type($structure)) {
if (!$partNumber) {
$partNumber = 1;
}
$text = imap_fetchbody($imap, $uid, $partNumber, FT_UID | FT_PEEK);
switch ($structure->encoding) {
case 3: return imap_base64($text);
case 4: return imap_qprint($text);
default: return $text;
}
}
// multipart
if ($structure->type == 1) {
foreach ($structure->parts as $index => $subStruct) {
$prefix = "";
if ($partNumber) {
$prefix = $partNumber . ".";
}
$data = $this->get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
if ($data) {
return $data;
}
}
}
}
return false;
}
/**
* extract mimetype
* taken from http://www.sitepoint.com/exploring-phps-imap-library-2/
*
* @return string mimetype
* @param $structure
*/
private function get_mime_type($structure) {
$primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
if ($structure->subtype) {
return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
}
return "TEXT/PLAIN";
}
/**
* get attachments of given email
* taken from http://www.sitepoint.com/exploring-phps-imap-library-2/
*
* @return array of attachments
* @param $imap stream
* @param $mailNum email
* @param $part
* @param $partNum
*/
private function getAttachments($imap, $mailNum, $part, $partNum) {
$attachments = array();
if (isset($part->parts)) {
foreach ($part->parts as $key => $subpart) {
if($partNum != "") {
$newPartNum = $partNum . "." . ($key + 1);
}
else {
$newPartNum = ($key+1);
}
$result = $this->getAttachments($imap, $mailNum, $subpart,
$newPartNum);
if (count($result) != 0) {
array_push($attachments, $result);
}
}
}
else if (isset($part->disposition)) {
if (strtolower($part->disposition) == "attachment") {
$partStruct = imap_bodystruct($imap, $mailNum,
$partNum);
$attachmentDetails = array(
"name" => $part->dparameters[0]->value,
"partNum" => $partNum,
"enc" => $partStruct->encoding,
"size" => $part->bytes
);
return $attachmentDetails;
}
}
return $attachments;
}
}
?>