How to Send Messages with Attachments

Definition

All the sendTo* methods can also attach a file. Sending an attachment is done with the attachmentFile or attachmentFiles keys. Currently only a single attachment per message is supported, so if using attachmentFiles array, make sure to send only a single entry.

client.messages.sendToUser(
userId: string|Object,
body: string,
options = {
attachmentFile: ?string|?Object,
attachmentFiles: ?Array<string|Object>,
deleteOnRead : ?boolean,
groupMetadata: ?Object,
groupName: ?string,
metadata : ?Object[]|?Object
organizationId: string, // if sender organizationId is different than recipient's
priority : ?string,
recipientOrganizationId: ?string, // defaults to senderOrganizationId
senderOrganizationId: string, // defaults to organizationId
ttl : ?number,
} : ?Object
):Promise<Message,Error>

Parameters

ParameterTypeDescription
userIdstring|ObjectUser ID
bodystring|numberMessage Body
options?ObjectOptions (described below)

Options

ParameterTypeDescription
attachmentFile?string|?ObjectAn attachment file. A shortcut to a single item in attachmentFiles.
attachmentFiles?Array<string|Object>A list of attachments. Currently only a single attachment is supported.
deleteOnRead?booleanWhether the message should be deleted on read (default: false)
groupMetadata?ObjectGroup metadata if sending to a group
groupName?stringGroup name if sending to a group
metadata?Object[]|?ObjectAn array of message metadata objects of extra information on the message.
organizationId?stringOrganization ID
priority?stringMessage priority. Values: NORMAL (default), HIGH
recipientOrganizationId?stringDefaults to senderOrganizationId
senderOrganizationIdstringDefaults to organizationId
ttl?numberTime to live in minutes. Organization settings might override this ttl.

Response

An error will be thrown if any of the arguments are invalid.

Otherwise, once the returned Promise is resolved, you will have access to the message object being sent

Example

Web

On the Web, attachmentFile takes an instance of File, which is available on an <input type="file"> files collection.

let file = inputFileReference.files[0];
const message = await client.messages.sendToUser("some-user-id", "hello!", {
organizationId: "some-org-id",
attachmentFile: file
});
console.log("sent", message.body, "with attachments", message.attachments);

Node.js

There's a slight difference between the web and the Node.js implementations:

In Node, attachmentFile can be either an absolute path to a local file (a string), or a Buffer object, that can be obtained by fs.readFile/fs.readFileSync.

let file = "/path/to/file.jpg";
// or
let file = fs.readFileSync("/path/to/file");
const message = await client.messages.sendToUser("some-user-id", "hello!", {
organizationId: "some-org-id",
attachmentFile: file
});
console.log("sent", message.body, "with attachments", message.attachments);