Php imap check if there is an email attachment

I am trying to create a small webmail application. When I read all emails in my inbox, I want to show for each mail if it has attachments. This works, but the problem is that it takes a long time, about 0.5s to attach a 1MB email. Multiply this by all emails in your Inbox with large attachments: | My question is, how do I check if there is an email by downloading all the email? Is it possible? Below is the code I am using now:

function existAttachment($part)
 { 
  if (isset($part->parts))
  { 
   foreach ($part->parts as $partOfPart)
   { 
    $this->existAttachment($partOfPart); 
   } 
  } 
  else
  { 
   if (isset($part->disposition))
   { 
    if ($part->disposition == 'attachment')
    { 
     echo '<p>' . $part->dparameters[0]->value . '</p>'; 
     // here you can create a link to the file whose name is  $part->dparameters[0]->value to download it 
     return true; 
    }   
   } 
  } 
  return false;
 }

 function hasAttachments($msgno)
 {
  $struct = imap_fetchstructure($this->_connection,$msgno,FT_UID); 
  $existAttachments = $this->existAttachment($struct);

  return $existAttachments;
 }

      

+3


source to share


2 answers


imap_fetchstructure

extracts all email content in order to analyze it. Unfortunately, there is no other way to test attachment.

Perhaps you can use the post size information from imap_headerinfo

to get a forecast if the post will have attachments.



Another way is to get emails at regular intervals in the background and save them with their content and UID for later database search. You should do this later when you want to find specific posts. (You don't want to scan the imap account when looking for "lunch")

+1


source


To check if there is an email attachment, use $ structure-> parts [0] -> parts.



$inbox = imap_open($mailserver,$username, $password, null, 1, ['DISABLE_AUTHENTICATOR' => 'PLAIN']) or die(var_dump(imap_errors()));

$unreadEmails = imap_search($inbox, 'UNSEEN');

$email_number = $unreadEmails[0];

$structure = imap_fetchstructure($inbox, $email_number);

if(isset($structure->parts[0]->parts))
{
   // has attachment
}else{
   // no attachment
}

      

0


source







All Articles