summaryrefslogtreecommitdiff
path: root/imap.php
blob: 01d8dae3af392b3697507affa3fc7982368674f3 (plain)
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
<?php
function date_compare($a, $b)
{
    $t1 = strtotime($a['date']);
    $t2 = strtotime($b['date']);
    return -($t1 - $t2);
}  

function getMail($user, $pass, $inbox, $max_items){
	$mail = array();

	foreach($inbox as $cur_inbox)  {
		try {
			$cur_mail = getMailbox($user, $pass, $max_items, $cur_inbox);
			if ( false === $cur_mail ) {
				// Mailbox is empty.
				continue;
			}
		} catch( Exception $e ) {
			header( $_SERVER["SERVER_PROTOCOL"] . " 403 Forbidden" );
			error_log($e->getMessage());
			exit(1);
		}

		$mail = array_merge($mail, $cur_mail);

	}

	usort($mail, 'date_compare');

	return $mail;
}

function getMailbox( $user, $password, $max_items, $inbox, $imap_host = "mx.iamfabulous.de" ) {
	require_once __DIR__ . '/vendor/autoload.php';

	$mailbox = new PhpImap\Mailbox('{'.$imap_host.'}'.$inbox, $user, $password);

	// Read all messaged into an array:
	$mailsIds = $mailbox->searchMailbox('ALL');
	if(!$mailsIds) {
	    #throw new Exception('Mailbox is empty');
	    return false;
	}

	$return = array();

	if ( (count($mailsIds) - $max_items) < 0) {
		$limit = 0;
	} else {
		$limit = count($mailsIds) - $max_items;
	}

	$cnt = 0;
	for( $i = count($mailsIds) - 1; $i >= $limit; $i-- ) {
		$mbox = $mailbox->getMail($mailsIds[$i], $markAsSeen = false);
		$return[$cnt]["date"] = $mbox->date;
		$return[$cnt]["subject"] = $mbox->subject;
		$return[$cnt]["fromName"] = $mbox->fromName;
		$return[$cnt]["fromAddress"] = $mbox->fromAddress;
		$return[$cnt]["to"] = $mbox->to;
		$return[$cnt]["toString"] = $mbox->toString;
		$return[$cnt]["messageId"] = $mbox->messageId;
		$return[$cnt]["textPlain"] = $mbox->textPlain;
		$return[$cnt]["textHtml"] = $mbox->textHtml;
		$return[$cnt]["mailbox"] = $inbox;
		$cnt++;
	}
	return $return;
}