Validate incoming e-mail attachment by filetype

Posted 1 month ago by oliverbusk

I am currently trying to validate incoming emails into my application and save the emails attachments to my database. However, I want to control which attachment types are allowed.

I use Mail-Mime-Parser for PHP, and the Laravel Inbound Mailbox package.

This is my code:

$attachments = collect($email->attachments())->map(function ($attachment) {
    return [
      'file' => $attachment-> getContentType()
    ];
})->validate(['file' => 'mimes:jpeg,jpg,bmp,png,gif,pdf']);

Above returns false, even though the incoming attachment is indeed a pdf file. This is the methods I have tried:

$attachment->getContentType(), whih returns:

Collection {#521
  #items: array:1 [
    0 => array:1 [
      "file" => "application/pdf"
    ]
  ]
}

I have also tried to return the actual content of the PDF file to file, but the validation still fails.

I have also tried to:

[...]->validate(['file' => 'mimetypes:application/pdf']); 

But it still returns false.

What am I doing wrong? How can I successfully validate the attachments mime filetype on the fly?

I am using Spaties Collection Macro for the validate() method.

For reference: This is the actual header content of the attachment, when I dd($email->attachments()):

  -headers: array:5 [
    0 => array:2 [
      0 => "Content-Type"
      1 => "application/pdf; name="Eksamenscase___BIGfinal.pdf""
    ]
    1 => array:2 [
      0 => "Content-Description"
      1 => "Eksamenscase___BIGfinal.pdf"
    ]
    2 => array:2 [
      0 => "Content-Disposition"
      1 => """
        attachment; filename="Eksamenscase___BIGfinal.pdf";\r\n
        \tsize=522462; creation-date="Sun, 03 Mar 2019 14:47:23 GMT";\r\n
        \tmodification-date="Sun, 03 Mar 2019 14:47:23 GMT"
        """
    ]
    3 => array:2 [
      0 => "Content-ID"
      1 => "<[email protected]>"
    ]
    4 => array:2 [
      0 => "Content-Transfer-Encoding"
      1 => "base64"
    ]
  ]

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.