I am so close to finishing this, but I'm stuck on downloading attachments.
So far I'm grabbing all my necessary email header information with the following code:
(also, I'm doing this via command line: CentOS 6)
<?php
echo "
";
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'myemail@mydomain.com';
$password = 'myfunpassword';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'ALL');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,1);
$output.= $email_number."
";
$output.= ($overview[0]->seen ? '[read]' : '[unread]')."
";
$output.= "date:".$overview[0]->date."
";
$output.= "to:".$overview[0]->to."
";
$output.= "from:".$overview[0]->from."
";
$output.= "size:".$overview[0]->size."
"; //size in bytes
$output.= "msgno:".$overview[0]->msgno."
";
$output.= "message_id:".$overview[0]->message_id."
"; //Message-ID
$output.= "uid:".$overview[0]->uid."
"; //UID the message has in the mailbox
$output.= "from:".$overview[0]->from."
";
$output.= "subject:".$overview[0]->subject."
";
/* output the email body */
$output.= "message:".$message;
/* detect attachments here */
$output.="
";
}
echo $output;
} // eof $emails check
imap_close($inbox);
?>
This works great! So now, I've got this code to tell me if there are attachments in each email:
<?php
// put this code above where it says "detect attachments here"
// attachments detection
$struct = imap_fetchstructure($inbox,$email_number);
$contentParts = count($struct->parts);
if ($contentParts >= 2) {
for ($i=2;$i<=$contentParts;$i++) {
$att[$i-2] = imap_bodystruct($inbox,$email_number,$i);
}
for ($k=0;$k<sizeof($att);$k++) {
if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII") {
if ($att[$k]->parameters[1]->value != "") {
$selectBoxDisplay[$k] = $att[$k]->parameters[1]->value;
}
} elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1") {
$selectBoxDisplay[$k] = $att[$k]->parameters[0]->value;
}
}
if (sizeof($selectBoxDisplay) > 0) {
for ($j=0;$j<sizeof($selectBoxDisplay);$j++) {
$output.= "
--file:". $selectBoxDisplay[$j]."";
}
}
}
// eof attachments detection
?>
And this works too! But now I'm to the point that I need to download the attachments, and most tutorials show me how to do it using from a browser's point of view, rather than the CLI. So I definitely need a little help here.
I'm expecting there's a way to determine where to download files on the server too.