openemail.files
Chaque méthode de cet espace de noms : sa signature, ses paramètres, ce qu'elle retourne et un exemple.
Méthodes
Every attachment the mailbox holds, sent and received, and the files uploaded to it, with their bytes, the download links they went out as and whether each can be deleted.
files.list()
List one page of the files the mailbox holds
list(options?: FileListOptions): Promise<Page<FileResource>>Resolves one page of the Files page: every attachment the mailbox holds, sent and received, and every file uploaded to it, with its name, type, size, the address it came to, the thread it belongs to and whether it can be deleted. listAll collects every page and iterate walks them lazily.
Only an upload that nothing depends on can be deleted, and its deletable is true. Every other row has a usage saying what keeps it: received, sent, linked for an upload that went out as a download link that still works, or scheduled for one attached to a message that has not gone out yet.
A key limited to particular addresses or domains sees only the files that arrived at them, the same boundary the thread list uses, so it does not see files uploaded for the whole workspace. A deleted file is not listed.
The index starts from the day it shipped, so an older mailbox lists what has arrived since. Older attachments are still on their messages, where threads.listAttachments reads them.
Paramètres
options.qstringSearches the file name and its type. Words match loosely, and a close spelling is tried when nothing matches exactly.
options.kindFileKindKeeps one kind:
image,pdf,audio,videoortext, the choices of the filter on the Files page.options.directionFileDirectionKeeps one direction:
inboundfor files that arrived on a message,outboundfor files that went out on one,uploadedfor files put on the Files page.options.addressstringKeeps the files of one address, the
deliveredToof the file, compared without regard to case.options.sinceDate | stringKeeps files added at or after this moment. A
Dateor an ISO 8601 string.options.untilDate | stringKeeps files added before this moment. A
Dateor an ISO 8601 string.options.sortFileSortnewest(the default),oldest,largestorname. A cursor carries on in the order it was handed out in.options.limitnumberPage size, from 1 to 100. The server defaults to 25.
options.cursorstringThe
nextCursorof the previous page. Leave it out for the first page.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
Page<FileResource> with items, hasMore and nextCursor. Each item has id, filename, mimeType, sizeBytes, direction, threadId, messageId, deliveredTo, usage, deletable and createdAt.
Exemple
const page = await openemail.files.list({ kind: 'pdf', sort: 'largest' }) console.log(page.items.map((file) => [file.filename, file.sizeBytes]))Remarques
Needs
files:read. Reading an email withthreads:readstill reads the attachments on it;files:readreads every file, uploads included.The cursor is opaque and holds where the last row sat in this order. A cursor this list did not hand out, or one handed out under another
sort, is a 400invalid_cursor.
Aussi disponible dans
files.listAll()
Collect every file into one array
listAll(options?: FileListOptions): Promise<Array<FileResource>>Walks every page of list and resolves with every file, in the order sort names. One request per page, with the same filters on each.
Paramètres
options.qstringSearches the file name and its type. Words match loosely, and a close spelling is tried when nothing matches exactly.
options.kindFileKindKeeps one kind:
image,pdf,audio,videoortext, the choices of the filter on the Files page.options.directionFileDirectionKeeps one direction:
inboundfor files that arrived on a message,outboundfor files that went out on one,uploadedfor files put on the Files page.options.addressstringKeeps the files of one address, the
deliveredToof the file, compared without regard to case.options.sinceDate | stringKeeps files added at or after this moment. A
Dateor an ISO 8601 string.options.untilDate | stringKeeps files added before this moment. A
Dateor an ISO 8601 string.options.sortFileSortnewest(the default),oldest,largestorname. A cursor carries on in the order it was handed out in.options.limitnumberPage size for each request, from 1 to 100. The server defaults to 25.
options.cursorstringStarts the walk after this cursor instead of the first page.
options.signalAbortSignalCancels the request in flight and the walk with it.
options.apiKeystringOverrides the client API key for every page of this walk.
Retourne
Array<FileResource> holding every file.
Exemple
const all = await openemail.files.listAll({ q: 'invoice' }) console.log(all.length)Remarques
If any page fails the promise rejects and the rows already fetched are discarded.
Aussi disponible dans
- API
GET /files
files.iterate()
Stream the files one at a time
iterate(options?: FileListOptions): AsyncGenerator<FileResource, void, undefined>Returns an async generator that yields one file at a time, in the order sort names, and requests the next page only once the current one is drained. Nothing is fetched until you consume it, and breaking out of the loop stops the requests.
Paramètres
options.qstringSearches the file name and its type. Words match loosely, and a close spelling is tried when nothing matches exactly.
options.kindFileKindKeeps one kind:
image,pdf,audio,videoortext, the choices of the filter on the Files page.options.directionFileDirectionKeeps one direction:
inboundfor files that arrived on a message,outboundfor files that went out on one,uploadedfor files put on the Files page.options.addressstringKeeps the files of one address, the
deliveredToof the file, compared without regard to case.options.sinceDate | stringKeeps files added at or after this moment. A
Dateor an ISO 8601 string.options.untilDate | stringKeeps files added before this moment. A
Dateor an ISO 8601 string.options.sortFileSortnewest(the default),oldest,largestorname. A cursor carries on in the order it was handed out in.options.limitnumberPage size for each request, from 1 to 100. The server defaults to 25.
options.cursorstringStarts the walk after this cursor instead of the first page.
options.signalAbortSignalCancels the request in flight and the walk with it.
options.apiKeystringOverrides the client API key for every page of this walk.
Retourne
AsyncGenerator<FileResource, void, undefined> yielding one file per step.
Exemple
for await (const file of openemail.files.iterate({ sort: 'oldest' })) { console.log(file.createdAt, file.filename)}Remarques
The generator is lazy, so an abandoned loop costs only the pages you consumed.
Aussi disponible dans
- API
GET /files
files.get()
Read one file by id
get(id: string, options?: RequestScope): Promise<FileResource>Resolves one file: its name, type, size, whether it was sent, received or uploaded, the address it came to, the thread and message it belongs to, and whether it can be deleted. download fetches its bytes.
deletable is true only for an upload that nothing depends on. Otherwise usage says what keeps it: received or sent for a file that came in or went out on a message, linked for an upload that went out as a download link that still works, and scheduled for one attached to a message that has not gone out yet.
Paramètres
idstringObligatoireThe id from
list,file_and 24 hex.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
FileResource, with usage and deletable.
Exemple
const file = await openemail.files.get('file_6bb640f5b99e47deb758f1f5') console.log(file.filename, file.mimeType)Remarques
A deleted file, one outside the addresses a narrowed key holds, and an unknown id all answer 404
resource_not_found.
Aussi disponible dans
files.stats()
Count the files and the space they take
stats(options?: RequestScope): Promise<FileStatsResource>Returns the numbers on the Analytics tab of the Files page in one request: how many files the mailbox holds and how many bytes they take, in all and split into received, sent and uploaded, the file types and the addresses taking the most space, how many files arrived on each of the last 30 days, and the download links still working with how often they were fetched.
Deleted files are not counted. A key limited to particular addresses or domains counts only the files that arrived at them, so files uploaded for the whole workspace are left out of its numbers.
Paramètres
options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
FileStatsResource with totals, received, sent and uploaded, each { files, bytes }, then types, byDay, addresses and links.
Exemple
const stats = await openemail.files.stats() console.log(`${stats.totals.files} files in ${stats.totals.bytes} bytes, ${stats.uploaded.files} of them uploaded`)console.log(stats.types.map((type) => [type.mimeType, type.bytes]))Remarques
Needs
files:read.typesholds at most the 8 types taking the most bytes andaddressesat most the 6 addresses holding the most. A file uploaded for the whole workspace has no address, so it counts in the totals and never inaddresses.byDaycovers the last 30 days in UTC, today included, and is sparse: a day on which no file arrived has no entry, so a chart must fill the gaps. EachdayisYYYY-MM-DD.linkscounts the download links that still work:sharesof them, fetcheddownloadstimes in all, last atlastDownloadAt, which is null when none was ever fetched. Scanners and link previewers are left out of the count.
Aussi disponible dans
files.download()
Fetch the bytes of a file
download(id: string, options?: RequestScope): Promise<Uint8Array>Resolves with the file exactly as it is stored, the same bytes the Download action on the Files page saves. The response carries the file's own Content-Type and name.
Paramètres
idstringObligatoireThe id from
list.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
Uint8Array holding the file.
Exemple
import { writeFile } from 'node:fs/promises' const file = await openemail.files.get('file_6bb640f5b99e47deb758f1f5')const bytes = await openemail.files.download(file.id) await writeFile(file.filename, bytes)Remarques
The whole file is held in memory, so fetch very large ones one at a time.
A file whose bytes are gone from storage answers 404 like a missing one.
Aussi disponible dans
files.listLinks()
List the download links a file went out as
listLinks(id: string, options?: ListOptions): Promise<Page<FileLinkResource>>Resolves one page of the download links made for this file, newest first. A large attachment sent from OpenEmail travels as a link rather than inside the message, and each send makes a link of its own. Every row says how often it was fetched, when last, and whether it was revoked. While one of its links still works, an upload cannot be deleted.
A file attached inside a message has no links, because nothing records when those are opened.
Paramètres
idstringObligatoireThe file id from
list.options.limitnumberPage size, from 1 to 100. The server defaults to 25.
options.cursorstringThe
nextCursorof the previous page. Leave it out for the first page.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
Page<FileLinkResource> with items, hasMore and nextCursor. Each item has id, url, host, downloads, lastDownloadAt, revokedAt and createdAt.
Exemple
const page = await openemail.files.listLinks('file_6bb640f5b99e47deb758f1f5') console.log(page.items.map((link) => [link.url, link.downloads]))Remarques
The count leaves out scanners and link previewers, the same classifier the
email.downloadedwebhook uses.
Aussi disponible dans
files.listAllLinks()
Collect every download link of a file into one array
listAllLinks(id: string, options?: ListOptions): Promise<Array<FileLinkResource>>Walks every page of listLinks and resolves with every download link of the file, newest first. One request per page, with the same filters on each.
Paramètres
idstringObligatoireThe file id from
list.options.limitnumberPage size for each request, from 1 to 100. The server defaults to 25.
options.cursorstringStarts the walk after this cursor instead of the first page.
options.signalAbortSignalCancels the request in flight and the walk with it.
options.apiKeystringOverrides the client API key for every page of this walk.
Retourne
Array<FileLinkResource> holding every download link of the file.
Exemple
const links = await openemail.files.listAllLinks('file_6bb640f5b99e47deb758f1f5') const fetched = links.reduce((sum, link) => sum + link.downloads, 0)Remarques
If any page fails the promise rejects and the rows already fetched are discarded.
Aussi disponible dans
files.iterateLinks()
Stream the download links of a file one at a time
iterateLinks(id: string, options?: ListOptions): AsyncGenerator<FileLinkResource, void, undefined>Returns an async generator that yields one link at a time, newest first, and requests the next page only once the current one is drained. Nothing is fetched until you consume it, and breaking out of the loop stops the requests.
Paramètres
idstringObligatoireThe file id from
list.options.limitnumberPage size for each request, from 1 to 100. The server defaults to 25.
options.cursorstringStarts the walk after this cursor instead of the first page.
options.signalAbortSignalCancels the request in flight and the walk with it.
options.apiKeystringOverrides the client API key for every page of this walk.
Retourne
AsyncGenerator<FileLinkResource, void, undefined> yielding one link per step.
Exemple
for await (const link of openemail.files.iterateLinks('file_6bb640f5b99e47deb758f1f5')) { console.log(link.url, link.revokedAt)}Remarques
The generator is lazy, so an abandoned loop costs only the pages you consumed.
Aussi disponible dans
files.createLink()
Publish a file at a public link
createLink(id: string, options?: FileLinkCreateOptions): Promise<FileLinkResource>Makes a public download link for the file and resolves with it. Anybody holding url can open the file without signing in, which is how an image or a document is referenced from an email or a web page. Each call makes a new link with its own download count, and a link keeps working until it is revoked with revokeLink or the file is deleted.
The link lives on the files host of options.domain when that domain has one set up, such as files.acme.com, else on the files host of the address the file belongs to, else on the OpenEmail API address. A file that came in or went out on a message is copied to public storage first. Programs and scripts are refused with 422 file_unshareable.
Paramètres
idstringObligatoireThe file id from
list.options.domainstringThe domain whose files host serves the link, such as
acme.com.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
FileLinkResource with id, url, host, downloads, lastDownloadAt, revokedAt and createdAt.
Exemple
const link = await openemail.files.createLink('file_6bb640f5b99e47deb758f1f5', { domain: 'acme.com' }) console.log(link.url)Remarques
Needs
files:write.Not retried after a lost response, because a second call makes a second link. Look for it with
listLinksfirst.
Aussi disponible dans
files.revokeLink()
Revoke a public link
revokeLink(id: string, linkId: string, options?: RequestScope): Promise<FileLinkResource>Stops a public link from working, for good, including in mail that already went out with it, and resolves with the link, revokedAt set. Revoking a link that is already revoked resolves with it unchanged, so the call is safe to repeat. An unknown link is a 404.
Paramètres
idstringObligatoireThe file id from
list.linkIdstringObligatoireThe link id from
listLinksorcreateLink.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
FileLinkResource with revokedAt set.
Exemple
await openemail.files.revokeLink('file_6bb640f5b99e47deb758f1f5', 'shr_2f9c4a1e7b3d')Remarques
Needs
files:write.
Aussi disponible dans
files.revokeAllLinks()
Revoke every link to a file
revokeAllLinks(id: string, options?: RequestScope): Promise<FileLinkRevocationResource>Makes the file private, as Make private on the Files page does: every public download link to it stops working at once, including the ones in mail that already went out. Resolves with revoked, how many links were still working. The file itself stays, and createLink can publish it again at a new link.
A key limited to particular addresses reaches only the files that arrived at them, and any other file is a 404.
Paramètres
idstringObligatoireThe file id from
list.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
FileLinkRevocationResource with fileId and revoked, the number of links that stopped working.
Exemple
const { revoked } = await openemail.files.revokeAllLinks('file_6bb640f5b99e47deb758f1f5') console.log(`${revoked} links stopped working`)Remarques
A file with no working links resolves with
revoked: 0, so the call is safe to repeat.Needs
files:write.
Aussi disponible dans
files.upload()
Upload a file to the Files page
upload(data: RawBody, options: FileUploadOptions): Promise<FileResource>Stores the bytes as a new file, the way the Upload button on the Files page does, and resolves with it: direction is uploaded, usage is null and deletable is true. Attach it to a send as { fileId } in emails.send, which is how a file larger than the inline cap goes out.
data is a Blob, an ArrayBuffer or a Uint8Array, sent as the request body. The name travels as the filename query parameter, and it is cleaned rather than refused: characters a file name cannot hold become _, and a name longer than 255 characters is cut, keeping its extension. The type is options.contentType, or a Blob's own type when that is left out, and application/octet-stream without either. A value that is not shaped like a MIME type is stored as application/octet-stream too.
A key limited to particular addresses or domains uploads to the first address it holds, which becomes deliveredTo. An unlimited key uploads for the whole workspace and deliveredTo is null, so a narrowed key never reaches that file afterwards.
Paramètres
dataRawBodyObligatoireThe file: a
Blob,ArrayBufferorUint8Array, not empty and at most 100 MB.options.filenamestringObligatoireThe name the file is stored and downloaded under, such as
report.pdf. A missing or blank name throws before anything is sent.options.contentTypestringThe MIME type, such as
application/pdf. Left out, aBlob's own type is used, elseapplication/octet-stream.options.timeoutMsnumberHow long the upload may take, in milliseconds. Left out, it is 10 minutes, or the client
timeoutMswhen that is longer.0waits as long as it takes.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
FileResource for the new file, with direction: 'uploaded', usage: null and deletable: true.
Exemple
import { openAsBlob } from 'node:fs' const file = await openemail.files.upload(await openAsBlob('report.pdf'), { filename: 'report.pdf', contentType: 'application/pdf' }) await openemail.emails.send({ from: '[email protected]', to: '[email protected]', subject: 'Your report', text: 'The report is attached.', attachments: [{ fileId: file.id }]})Remarques
Needs
files:write, the same scope that deletes files.The SDK does not retry an upload, because a second attempt after a lost response could store the file twice. Look for it with
listbefore trying again.An empty file is a 400
upload_empty, a program or script, judged by its name, is a 400upload_dangerous, and a file over 100 MB is a 413upload_too_large. A key limited to addresses that holds none is a 403upload_no_address.A workspace keeps up to 10 GB of uploads, and past that a 507
upload_storage_fullholds until some are deleted. It takes 500 uploads an hour, deleted ones included, and more is a 429upload_rate_limited. A 502upload_failedmeans storage failed and nothing was kept, so it is safe to try again.
Aussi disponible dans
files.delete()
Delete an uploaded file for good
delete(id: string, options?: RequestScope): Promise<DeletedFileResource>Removes an uploaded file: its bytes are deleted from storage and it leaves the Files page. The row stays, marked deleted, so the index knows the file existed. There is no undo.
Only an upload that nothing depends on can be deleted, the files whose deletable is true. A file that was received or sent stays with its message, and so does an upload that went out as a download link that still works or is attached to a message that has not gone out yet. Those are refused with 409 file_in_use, and the message names the file and says why. An upload that was sent inside a message can still be deleted, because the message keeps its own copy, which is listed as a separate sent file.
deleteMany deletes up to 100 in one call and reports the ones it kept instead of failing.
Paramètres
idstringObligatoireThe id from
list.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
DeletedFileResource, { object: 'file', id, deleted: true }.
Exemple
try { const removed = await openemail.files.delete('file_6bb640f5b99e47deb758f1f5') console.log(removed.deleted)} catch (error) { if (error instanceof OpenEmailApiError && error.code === 'file_in_use') console.log(error.message) else throw error}Remarques
Needs
files:write, the same scope that uploads. A key limited to some addresses may delete only files that arrived at them, so an upload made for the whole workspace answers it 404.A file that is unknown, already deleted or out of reach answers 404
resource_not_found. A file in use answers 409file_in_usewithparam: 'id', and itsusageongetsays which rule keeps it.The SDK does not retry a delete. A 404 on your own second attempt after a lost response means the first one worked.
Aussi disponible dans
files.deleteMany()
Delete up to 100 files in one call
deleteMany(ids: Array<string>, options?: RequestScope): Promise<FileBatchDeleteResource>Deletes every file in ids that can be deleted, the way delete deletes one, and reports the rest instead of failing. It is what selecting several files on the Files page and pressing Delete does.
Only an uploaded file that nothing depends on can be deleted. A file that was received or sent stays with its message, and so does an upload that went out as a download link that still works or is attached to a message that has not gone out yet. Each of those comes back in kept with its usage and a reason in plain words. An id that is unknown, already deleted or outside the addresses a narrowed key holds comes back in missing. The rule is checked again at the moment of deleting, so a file that became used in between is kept.
There is no undo.
Paramètres
idsArray<string>Obligatoire1 to 100 file ids from
list. More than 100, or none, is a 422 onids. A repeated id counts once.options.signalAbortSignalCancels the request.
options.apiKeystringOverrides the client API key for this call only.
Retourne
FileBatchDeleteResource, { object: 'file_batch_delete', deleted, kept, missing }. deleted and missing hold ids, and each entry of kept is { id, filename, usage, reason }.
Exemple
const result = await openemail.files.deleteMany(['file_6bb640f5b99e47deb758f1f5', 'file_0c3e2a91d4b7f6058e1a2b3c']) console.log(`${result.deleted.length} deleted`) for (const file of result.kept) console.log(file.filename, file.reason)Remarques
Needs
files:write, the same scope that uploads.A partial result resolves rather than rejects, so read
keptandmissingto see what stayed.The SDK does not retry it. Calling it again after a lost response reports the files the first call deleted in
missing.To clear out every upload that can go, keep the rows of
listAllwhosedeletableis true and pass their ids 100 at a time.