PHP | How to send a multipart message with an attachment larger than 3 MB using PHP?

Here is a PHP code snippet that works to send a multipart message with an attachment larger than 3 MB.

<?php

function sendEmailWithAttachments($token, $grantId, $subject, $body, $recipientName, $recipientEmail, $attachments) {
    $curl = curl_init();

    $headers = [
        "Authorization: Bearer $token",
        "Content-Type: multipart/form-data"
    ];

    // Dynamic generation of attachment field names
    $postFields = [
        'message' => json_encode([
            'subject' => $subject,
            'body' => $body,
            'to' => [
                [
                    'name' => $recipientName,
                    'email' => $recipientEmail
                ]
            ]
        ])
    ];

    // Adding the attachments dynamically
    foreach ($attachments as $attachment) {
        // Create a unique identifier for each attachment
        $identifier = uniqid('attachment_', true);
        $postFields[$identifier] = new CURLFile($attachment);
    }

    curl_setopt_array($curl, [
        CURLOPT_URL => "https://api.us.nylas.com/v3/grants/$grantId/messages/send",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_VERBOSE => true,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postFields
    ]);

    $response = curl_exec($curl);

    if (curl_errno($curl)) {
        echo 'Error:' . curl_error($curl);
    }

    curl_close($curl);

    return $response;
}

// Example usage
$token = 'TOKEN-REDACTED'; // Replace with your actual token
$grantId = 'your-grant-id-here'; // Replace with your grant ID
$subject = 'Happy Birthday from Nylas!';
$body = "Wishing you the happiest of birthdays. \n Fondly, \n -Nylas";
$recipientName = 'Jacob Doe';
$recipientEmail = 'jacob.doe@example.com';
$attachments = [
    '/path/to/file',
    '/path/to/file2'
];

$response = sendEmailWithAttachments($token, $grantId, $subject, $body, $recipientName, $recipientEmail, $attachments);

echo $response;
?>

 

References

Sending attachments in API V3 larger than 3MB via multipart

 

Updated

Was this article helpful?

0 out of 0 found this helpful

Have more questions? Submit a request

Comments

0 comments

Please sign in to leave a comment.