0

I'd like to send mail via the Graph API and attach a file by its drive item ID.

At the moment I can successfully send email via the Graph API and attach a file that is on my local server.

However the file originates on OneDrive so the current situation is I have to download the file to my server then re-upload it via the sendMail endpoint as an attachment and then delete it from my server.

This seems like an unneeded step if it's possible to just provide the file ID and let office 365 resolve it all locally.

$mailBody = ...
    'attachments' => [
        [
            '@odata.type' => '#microsoft.graph.fileAttachment',
            'Name' => 'file.docx',
            'ContentBytes' => $localFile
            // 'DriveID' => 'possibly this instead of Content Bytes?'
        ]
     ]
     ...

$response = $this->getGraph()->createRequest("POST", "/users/{primary-user}/sendMail")
                ->attachBody($mailBody)
                ->execute();
Royal Wares
  • 1,192
  • 10
  • 23

1 Answers1

-1

You can attach a file by its drive item ID, it is called referenceAttachment but not the fileAttachment in your code. The v1.0 edition has very limited support for referenceAttachment. And by that I mean, there isn't much you can do with them beyond acknowledging one exists.

Reference from egorbunov's answer: Send reference attachment to email via Graph API

Create the message draft using POST request to https://graph.microsoft.com/beta/me/messages with payload:

{
    "subject": "TestMessage",
    "toRecipients": [
        {
            "emailAddress":{
                "address":"egor-mailbox@ya.ru"
            }
        }
    ],
    "body": {
        "contentType": "html",
        "content": "<b>Hello!</b>"
    }
},

As a response you will get the whole message structure with id set to something like

AQMkADAwATMwMAItMTJkYi03YjFjLTAwAi0wMAoARgAAA_hRKmxc6QpJks9QJkO5R50HAP6mz4np5UJHkvaxWZjGproAAAIBDwAAAP6mz4np5UJHkvaxWZjGproAAAAUZT2jAAAA. Lets refer to it as {messageID}. NOTE: as you can see I have passed html-typed body. This is needed because (at least in GraphAPI Explorer) graph api returns error in case you are trying to add reference attachment to message with non-html body content-type.

After that you can create an attachment using POST request to https://graph.microsoft.com/beta/me/messages/{messageID}/attachments

{
    "@odata.type": "#microsoft.graph.referenceAttachment",
    "name": "AttachmentName",
    "sourceUrl": "https://1drv.ms/u/s!ASDLKASDLASHDLASKDLJAXCXZ_DASD",
    "providerType": "oneDriveConsumer",
    "isFolder": false
}

After step 2 you will see created message in your mailbox Drafts folder. To send it use

https://graph.microsoft.com/beta/me/messages/{messageID}/send (=( turns out it does not work too)

An alternative solution, not add attachment but add the file link in the mail body directly(Let the recipient to download it as needed).

Seiya Su
  • 1,836
  • 1
  • 7
  • 10