PHP Mailgun attachment implementation throwing array resource error

I’m working with Mailgun’s email service in my PHP project and running into trouble when trying to include file attachments. Everything works fine for basic email sending, but as soon as I try to add the attachment array following their docs, I keep getting this frustrating error message about invalid resource type array in the PSR7 functions file.

The error specifically mentions /vendor/guzzlehttp/psr7/src/functions.php which makes me think it’s related to how I’m formatting the attachment data. I’ve tried different approaches but can’t seem to get it right.

Here’s my current code setup:

$mailgunClient = new Mailgun('my-api-key');
$domainName = "my-domain.com";
$emailData = array(
    'from' => '[email protected]',
    'to' => $recipient,
    'subject' => $emailSubject,
    'html' => $messageBody,
    'attachment' => [
        [
            'filePath' => $documentPath,
            'filename' => $documentName
        ]
    ]
);

$response = $mailgunClient->sendMessage($domainName, $emailData);

Any ideas what I’m doing wrong with the attachment structure?

yea, classic Mailgun PHP SDK issue. ur passing the file path as a string, but it wants the actual file resource. use fopen($documentPath, 'r') instead of just the path. don’t forget fclose() afterward or u’ll get memory leaks.

This happens because of how Mailgun’s API handles attachments. Don’t use nested arrays with filePath and filename keys - you need to structure the attachment parameter differently based on your SDK version. For newer Mailgun SDKs, try this instead: ‘attachment’ => [[‘filedata’ => file_get_contents($documentPath), ‘filename’ => $documentName]]. Sometimes you’ll need to pass attachments as a completely separate parameter rather than stuffing them in the main email data array. That PSR7 error means Guzzle’s getting the wrong data type when it builds the HTTP request - usually happens when the SDK expects binary data but gets structured arrays. I ran into the same thing migrating between SDK versions. Reading the file contents directly fixed the resource type conflicts for me.

Your attachment formatting is incorrect for the Mailgun PHP SDK. It requires actual file resources or CURLFile objects instead of just file path arrays like you’re using. I faced this same issue a few months ago and spent a lot of time figuring it out.

Change your attachment array to use CURLFile objects:

‘attachment’ => [
new CURLFile($documentPath, mime_content_type($documentPath), $documentName)
]

Alternatively, you could open the file first and use file resources, but CURLFile is cleaner and automatically detects the MIME type for you. The PSR7 error occurs because Guzzle expects valid file resources for HTTP multipart requests and doesn’t know how to process string paths in arrays.