Joel Hackney
Joel Hackney

Reputation: 147

parsing email attachments in php

I have a .forward.postix that is piping incoming emails to a shell account, and consequently to a PHP script that parses the emails - awesome.

As of now, and based on everything I've seen online, I'm using the explode('From: ', $email); approach to split everything down into the vars I need for my database.

Enter attachments! Using the same approach, I'm doing this to pull out a jpg attachment - but it appears not every email client formats the raw source the same way and it's causing some headaches!

$contentType1 = explode('Content-type: image/jpg;', $email); //start ContentType
$contentType2 = explode("--Boundary_", $contentType1[1]); //end ContentType

$jpg1 = explode("\n\n", $contentType2[0]); //double return starts base64 blob
$jpg2 = explode("\n\n", $jpg1[1]); //double return marks end of base64 blob

$image = base64_decode($jpg2[0]); //decode base64 blob into jpg raw

Here's my issue: Not all mail clients - like GMail for example - list an attachment as 'Content-type: image/jpg'. GMail puts in 'Content-Type: IMAGE/JPEG' and sometimes sends it as 'Content-Type: image/jpeg'! Which don't match my explode...

My Question: Does someone know a better way of finding the bounds of a base64 blob? or maybe a case-insensitive way of exploding the 'Content-Type:' so I can then try against image/jpg or image-jpeg to see what matches?

Upvotes: 0

Views: 998

Answers (1)

Mike Brant
Mike Brant

Reputation: 71384

You can try to split your string using preg_split(). Maybe something like this

$pattern = '#content-type: image/jpe?g#i';
$split_array = preg_split($pattern, $email);

Upvotes: 1

Related Questions