Example #1
0
 protected function processAttachment(Message &$message, Part $part)
 {
     $name = NULL;
     $filename = NULL;
     $contentType = NULL;
     $headers = $part->getHeaders();
     $attachment = new Attachment($part);
     // Get the filename and/or name for the attachment. Try the
     // disposition first.
     if ($headers->has('content-disposition')) {
         $name = $part->getHeaderField('content-disposition', 'name');
         $filename = $part->getHeaderField('content-disposition', 'filename');
     }
     if ($headers->has('content-type')) {
         $contentType = strtolower($part->getHeaderField('content-type'));
         $name = $name ?: $part->getHeaderField('content-type', 'name');
         $filename = $filename ?: $part->getHeaderField('content-type', 'filename');
     }
     // Store this before overwriting
     $attachment->origName = $name;
     $attachment->origFilename = $filename;
     // Certain mime types don't provide name info but we can try
     // to infer it from the mime type.
     if (!$filename && $headers->has('content-id')) {
         $filename = trim($part->getHeaderField('content-id'), " <>");
     }
     if (!$filename && $headers->has('x-attachment-id')) {
         $filename = trim($part->getHeaderField('x-attachment-id'), " <>");
     }
     // Content-Location can be the URL path to a file. If this exists
     // then try to get the filename from this path.
     if (!$filename && $headers->has('content-location')) {
         $filename = basename($part->getHeaderField('content-location'));
     }
     // If it's a calendar event then let's give it a nice name
     if (!$filename && $contentType === 'text/calendar') {
         $filename = 'event.ics';
     }
     if (!$filename) {
         $filename = $name;
     }
     if (!$filename) {
         $filename = 'noname';
     }
     // Try to add an extension if it's missing one
     File::addExtensionIfMissing($filename, $contentType);
     // If we are fortunate enough to get an attachment ID, then
     // use that. Otherwise we want to create on in a deterministic
     // way.
     $attachment->name = $name;
     $attachment->filename = $filename;
     $attachment->mimeType = $contentType;
     $attachment->generateId($message);
     // Attachments are saved in YYYY/MM directories
     if ($this->attachmentsDir) {
         $attachment->generateFilepath($message, $this->attachmentsDir);
         $this->debug("Before writing attachment to disk");
         $attachment->saveToFile();
         $this->debug("After file_put_contents finished");
     }
     $message->addAttachment($attachment);
     $this->debug("New attachment created");
 }