php upload email attachment to file

Started on the old forum in January 2012 · view the original in the archive · old links redirect here

No replies · 935 views · started 14 years ago · 1 min read

GumSlone Administrator Principal · 1,690 posts #1

here is a php script which saves email attachments to files into a specified directory.

<?php

$subject_password = 'asdfdfgg'; /* set upload password for subject, the emails with upload files should have this password in the subject */

$upload_path = './uploads'; //withoult last slash and chmod 0777

$mbox = imap_open("{mail.yourhost.com:143/imap/notls}INBOX", "upload@yourhost.com", "password")or die("Connection to server failed");
$headers = imap_headers($mbox) or die("Couldn't get emails");
$numEmails = sizeof($headers);
for($i = 1; $i <= $numEmails; $i++) 
{

    $header = imap_headerinfo($mbox, $i); 

    $from = $header->fromaddress; 

    $subject = strip_tags($header->subject); 
    
    $date = $header->date;
    
    $info = imap_fetchstructure($mbox, $i);
    

     if(stristr($subject, $subject_password))
    {
  // find out how may parts the object has
  $numparts = count($info->parts);
  
  for($k=0;$k<$numparts;$k++)
  {
   if($info->parts[$k]->dparameters[0]->attribute=='filename')
   {
    
    //attachment to array
    $a['file_size'] = $info->parts[$k]->bytes;
    $a['file_type'] = $info->parts[$k]->subtype;
    $a['file_name'] = $info->parts[$k]->dparameters[0]->value;
    $a['file_from'] = $header->from[0]->mailbox . "@" . $header->from[0]->host;
    $a['file_content'] = base64_decode(imap_fetchbody($mbox, $i, $k+1));
    $att[] = $a;
   }
  }
    }

    imap_delete($mbox, (int)$i);
}
imap_expunge($mbox);
imap_close($mbox);

for($l=0;$l<count($att);$l++)
{
    file_put_contents($upload_path.'/'.$att[$l]['file_name'], $att[$l]['file_content']);
}

?>

Advertise your mobile site for FREE with AdTwirl

External image (may be gone)

Write your reply now; next you create a free account (or sign in) and it is posted right away. Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close