Перейти к документации
C#

client.Files

Каждый метод этого пространства имён: его сигнатура, параметры, что он возвращает, и пример.

Методы

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.ListAsync

List one page of the files the mailbox holds

Разрешенияfiles:readПостранично перебирает результаты
Сигнатура
Task<Page> ListAsync(    string? q = null,    string? kind = null,    string? direction = null,    string? address = null,    DateTimeOffset? since = null,    DateTimeOffset? until = null,    string? sort = null,    int? limit = null,    string? cursor = null,    string? apiKey = null,    CancellationToken cancellationToken = default)

Returns 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. Files.ListAllAsync collects every page and Files.IterateAsync 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.ListAttachmentsAsync reads them.

Параметры

qstring?

Searches the file name and its type. Words match loosely, and a close spelling is tried when nothing matches exactly.

kindstring?

Keeps one kind: image, pdf, audio, video or text, the choices of the filter on the Files page, also in OpenEmail\Constants\FileKinds.

directionstring?

Keeps one direction: inbound for files that arrived on a message, outbound for files that went out on one, uploaded for files put on the Files page.

addressstring?

Keeps the files of one address, the deliveredTo of the file, compared without regard to case.

sinceDateTimeOffset?

Keeps files added at or after this moment. A DateTimeOffset.

untilDateTimeOffset?

Keeps files added before this moment. A DateTimeOffset.

sortstring?

newest (the default), oldest, largest or name, also in OpenEmail\Constants\FileSorts. A cursor carries on in the order it was handed out in.

limitint?

Page size, from 1 to 100. The server defaults to 25.

cursorstring?

The nextCursor of the previous page. Leave it out for the first page.

apiKeystring?

Overrides the client's API key for this call only.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A Page of file objects, with items, hasMore and nextCursor. Each item has id, filename, mimeType, sizeBytes, direction, threadId, messageId, deliveredTo, usage, deletable and createdAt.

Пример

using OpenEmail.Constants; var page = await client.Files.ListAsync(kind: FileKinds.Pdf, since: DateTimeOffset.UtcNow.AddDays(-30), sort: FileSorts.Largest, limit: 10); foreach (var file in page){    Console.WriteLine($"{file["filename"]} {file["sizeBytes"]} bytes, {file["usage"]?.ToString() ?? "unused"}{((bool?)file["deletable"] == true ? ", can be deleted" : "")}");}

Примечания

  • Needs files:read. Reading an email with threads:read still reads the attachments on it, while files:read reads 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 400 invalid_cursor.

Также доступно в

API
GET /files
TypeScript
files.list()
Python
files.list()
Ruby
files.list
PHP
files->list
Go
Files.List
Java
files().list
CLI
openemail files list

Files.ListAllAsync

Collect every file into one object

Разрешенияfiles:readПостранично перебирает результаты
Сигнатура
Task<IReadOnlyList<JsonObject>> ListAllAsync(    string? q = null,    string? kind = null,    string? direction = null,    string? address = null,    DateTimeOffset? since = null,    DateTimeOffset? until = null,    string? sort = null,    int? limit = null,    string? cursor = null,    string? apiKey = null,    CancellationToken cancellationToken = default)

Walks every page of Files.ListAsync and returns every file in one object, in the order sort: names. One request per page, with the same filters on each.

Параметры

qstring?

Searches the file name and its type. Words match loosely, and a close spelling is tried when nothing matches exactly.

kindstring?

Keeps one kind: image, pdf, audio, video or text, the choices of the filter on the Files page.

directionstring?

Keeps one direction: inbound for files that arrived on a message, outbound for files that went out on one, uploaded for files put on the Files page.

addressstring?

Keeps the files of one address, the deliveredTo of the file, compared without regard to case.

sinceDateTimeOffset?

Keeps files added at or after this moment. A DateTimeOffset.

untilDateTimeOffset?

Keeps files added before this moment. A DateTimeOffset.

sortstring?

newest (the default), oldest, largest or name. A cursor carries on in the order it was handed out in.

limitint?

Page size for each request, from 1 to 100. The server defaults to 25.

cursorstring?

Starts the walk after this cursor instead of the first page.

apiKeystring?

Overrides the client's API key for every page of this walk.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A list of file objects holding every file, each with the fields Files.ListAsync returns.

Пример

var invoices = await client.Files.ListAllAsync(q: "invoice", limit: 100); Console.WriteLine(invoices.Count);

Примечания

  • If any page fails, the exception is thrown and the rows already fetched are discarded.

Также доступно в

API
GET /files
TypeScript
files.listAll()
Python
files.list_all()
Ruby
files.list_all
PHP
files->listAll
Go
Files.ListAll
Java
files().listAll

Files.IterateAsync

Stream the files one at a time

Разрешенияfiles:readПостранично перебирает результаты
Сигнатура
IAsyncEnumerable<JsonObject> IterateAsync(    string? q = null,    string? kind = null,    string? direction = null,    string? address = null,    DateTimeOffset? since = null,    DateTimeOffset? until = null,    string? sort = null,    int? limit = null,    string? cursor = null,    string? apiKey = null,    CancellationToken cancellationToken = default)

Returns an IAsyncEnumerable<JsonObject> that yields one file at a time, in the order sort: names, and requests the next page only once the current one is used up. Nothing is fetched until the loop starts, and breaking out of the await foreach stops the requests.

Параметры

qstring?

Searches the file name and its type. Words match loosely, and a close spelling is tried when nothing matches exactly.

kindstring?

Keeps one kind: image, pdf, audio, video or text, the choices of the filter on the Files page.

directionstring?

Keeps one direction: inbound for files that arrived on a message, outbound for files that went out on one, uploaded for files put on the Files page.

addressstring?

Keeps the files of one address, the deliveredTo of the file, compared without regard to case.

sinceDateTimeOffset?

Keeps files added at or after this moment. A DateTimeOffset.

untilDateTimeOffset?

Keeps files added before this moment. A DateTimeOffset.

sortstring?

newest (the default), oldest, largest or name. A cursor carries on in the order it was handed out in.

limitint?

Page size for each request, from 1 to 100. The server defaults to 25.

cursorstring?

Starts the walk after this cursor instead of the first page.

apiKeystring?

Overrides the client's API key for every page of this walk.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

An IAsyncEnumerable<JsonObject> that yields one file per step.

Пример

using OpenEmail.Constants; await foreach (var file in client.Files.IterateAsync(direction: FileDirections.Uploaded, sort: "oldest")){    if ((bool?)file["deletable"] == true)    {        Console.WriteLine($"{file["createdAt"]} {file["filename"]} can go");    }}

Примечания

  • The generator is lazy, so an abandoned loop costs only the pages you consumed.

Также доступно в

API
GET /files
TypeScript
files.iterate()
Python
files.iterate()
Ruby
files.iterate
PHP
files->iterate
Go
Files.Iterate
Java
files().iterate

Files.GetAsync

Read one file by id

Разрешенияfiles:read
Сигнатура
Task<JsonObject> GetAsync(    string id,    string? apiKey = null,    CancellationToken cancellationToken = default)

Returns 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. Files.DownloadAsync 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.

Параметры

idstringОбязательно

The id from Files.ListAsync, file_ and 24 hex.

apiKeystring?

Overrides the client's API key for this call only.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A JsonObject with the fields Files.ListAsync returns for each file, usage and deletable included.

Пример

var file = await client.Files.GetAsync("file_6bb640f5b99e47deb758f1f5"); Console.WriteLine($"{file["filename"]} ({file["mimeType"]}) in thread {file["threadId"]?.ToString() ?? "none"}"); if ((bool?)file["deletable"] != true){    Console.WriteLine($"Kept because it is {file["usage"]}");}

Примечания

  • A deleted file, one outside the addresses a narrowed key holds, and an unknown id all answer 404 resource_not_found.

Также доступно в

API
GET /files/{id}
TypeScript
files.get()
Python
files.get()
Ruby
files.get
PHP
files->get
Go
Files.Get
Java
files().get
CLI
openemail files get

Files.StatsAsync

Count the files and the space they take

Разрешенияfiles:read
Сигнатура
Task<JsonObject> StatsAsync(string? apiKey = null, CancellationToken cancellationToken = default)

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.

Параметры

apiKeystring?

Overrides the client's API key for this call only.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A JsonObject with totals, received, sent and uploaded, each an object of files and bytes, then types, byDay, addresses and links.

Пример

var stats = await client.Files.StatsAsync(); Console.WriteLine($"{stats["totals"]?["files"]} files in {stats["totals"]?["bytes"]} bytes, {stats["uploaded"]?["files"]} of them uploaded"); foreach (var type in stats["types"]?.AsArray() ?? []){    Console.WriteLine($"{type?["mimeType"]}: {type?["bytes"]} bytes");}

Примечания

  • Needs files:read.

  • types holds at most the 8 types taking the most bytes and addresses at 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 in addresses.

  • byDay covers 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. Each day is YYYY-MM-DD.

  • links counts the download links that still work: shares of them, fetched downloads times in all, last at lastDownloadAt, which is null when none was ever fetched. Scanners and link previewers are left out of the count.

Также доступно в

API
GET /files/stats
TypeScript
files.stats()
Python
files.stats()
Ruby
files.stats
PHP
files->stats
Go
Files.Stats
Java
files().stats
CLI
openemail files stats

Files.DownloadAsync

Fetch the bytes of a file

Разрешенияfiles:read
Сигнатура
Task<byte[]> DownloadAsync(    string id,    string? apiKey = null,    CancellationToken cancellationToken = default)

Returns 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.

Параметры

idstringОбязательно

The id from Files.ListAsync.

apiKeystring?

Overrides the client's API key for this call only.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A string holding the bytes of the file.

Пример

var file = await client.Files.GetAsync("file_6bb640f5b99e47deb758f1f5"); var bytes = await client.Files.DownloadAsync(file["id"]!.GetValue<string>()); await File.WriteAllBytesAsync(Path.GetFileName((string?)file["filename"] ?? "download"), bytes); Console.WriteLine($"{bytes.Length} bytes saved");

Примечания

  • 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.

Также доступно в

API
GET /files/{id}/content
TypeScript
files.download()
Python
files.download()
Ruby
files.download
PHP
files->download
Go
Files.Download
Java
files().download
CLI
openemail files download

Files.UploadAsync

Upload a file to the Files page

Разрешенияfiles:write
Сигнатура
Task<JsonObject> UploadAsync(    Stream data,    string filename,    string? contentType = null,    TimeSpan? timeout = null,    string? apiKey = null,    CancellationToken cancellationToken = default)

Stores the bytes as a new file, the way the Upload button on the Files page does, and returns it: direction is uploaded, usage is null and deletable is true. Attach it to a send as new Body { ["fileId"] = file["id"] } in the attachments of Emails.SendAsync, which is how a file larger than the inline cap goes out.

data is a readable Stream, 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 contentType:, and application/octet-stream without it. 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.

Параметры

dataStreamОбязательно

The file: a readable Stream, not empty and at most 100 MB.

filenamestringОбязательно

The name the file is stored and downloaded under, such as report.pdf. A missing or blank name throws an ArgumentException before anything is sent.

contentTypestring?

The MIME type, such as application/pdf. Left out, it is application/octet-stream.

timeoutTimeSpan?

How long the upload may take. Left out, it is 10 minutes, or the client's Timeout when that is longer. TimeSpan.Zero or Timeout.InfiniteTimeSpan waits as long as it takes, and a negative value throws an ArgumentException.

apiKeystring?

Overrides the client's API key for this call only.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A JsonObject for the new file, with direction set to uploaded, usage null and deletable true.

Пример

await using var report = File.OpenRead("report.csv"); var file = await client.Files.UploadAsync(report, "q3-report.csv", timeout: TimeSpan.FromSeconds(120)); Console.WriteLine($"Uploaded {file["id"]} as {file["filename"]} ({file["mimeType"]})"); await using var invoiceFile = File.OpenRead("invoice.pdf"); var invoice = await client.Files.UploadAsync(invoiceFile, "invoice.pdf", contentType: "application/pdf"); Console.WriteLine($"{invoice["sizeBytes"]} bytes stored as {invoice["id"]}");

Примечания

  • 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 Files.ListAsync before trying again.

  • An empty file is a 400 upload_empty, a program or script, judged by its name, is a 400 upload_dangerous, and a file over 100 MB is a 413 upload_too_large. A key limited to addresses that holds none is a 403 upload_no_address.

  • A workspace keeps up to 10 GB of uploads, and past that a 507 upload_storage_full holds until some are deleted. It takes 500 uploads an hour, deleted ones included, and more is a 429 upload_rate_limited. A 502 upload_failed means storage failed and nothing was kept, so it is safe to try again.

Также доступно в

API
POST /files
TypeScript
files.upload()
Python
files.upload()
Ruby
files.upload
PHP
files->upload
Go
Files.Upload
Java
files().upload
CLI
openemail files upload

Files.DeleteAsync

Delete an uploaded file for good

Разрешенияfiles:write
Сигнатура
Task<JsonObject> DeleteAsync(    string id,    string? apiKey = null,    CancellationToken cancellationToken = default)

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.

Files.DeleteManyAsync deletes up to 100 in one call and reports the ones it kept instead of failing.

Параметры

idstringОбязательно

The id from Files.ListAsync.

apiKeystring?

Overrides the client's API key for this call only.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A JsonObject with object set to file, id and deleted set to true.

Пример

try{    await client.Files.DeleteAsync("file_6bb640f5b99e47deb758f1f5");     Console.WriteLine("Deleted");}catch (OpenEmailApiException error) when (error.IsConflict){    Console.WriteLine($"Kept: {error.Message}");}

Примечания

  • 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 409 file_in_use with param set to id, and its usage on Files.GetAsync says 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.

Также доступно в

API
DELETE /files/{id}
TypeScript
files.delete()
Python
files.delete()
Ruby
files.delete
PHP
files->delete
Go
Files.Delete
Java
files().delete
CLI
openemail files delete

Files.DeleteManyAsync

Delete up to 100 files in one call

Разрешенияfiles:write
Сигнатура
Task<JsonObject> DeleteManyAsync(    IEnumerable<string> ids,    string? apiKey = null,    CancellationToken cancellationToken = default)

Deletes every file in ids that can be deleted, the way Files.DeleteAsync 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.

Параметры

idsIEnumerable<string>Обязательно

1 to 100 file ids from Files.ListAsync. More than 100, or none, is a 422 on ids. A repeated id counts once.

apiKeystring?

Overrides the client's API key for this call only.

cancellationTokenCancellationToken

Cancels the request.

Возвращает

A JsonObject with object set to file_batch_delete, deleted, kept and missing. deleted and missing hold ids, and each entry of kept is an object with id, filename, usage and reason.

Пример

var result = await client.Files.DeleteManyAsync(new[] { "file_6bb640f5b99e47deb758f1f5", "file_0c3e2a91d4b7f6058e1a2b3c" }); Console.WriteLine($"{result["deleted"]?.AsArray().Count} deleted, {result["missing"]?.AsArray().Count} not found"); foreach (var kept in result["kept"]?.AsArray() ?? []){    Console.WriteLine($"Kept {kept?["filename"]} ({kept?["usage"]}): {kept?["reason"]}");}

Примечания

  • Needs files:write, the same scope that uploads.

  • A partial result returns rather than throws, so read kept and missing to 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 Files.ListAllAsync whose deletable is true and pass their ids 100 at a time.

Также доступно в

API
POST /files/batch-delete
TypeScript
files.deleteMany()
Python
files.delete_many()
Ruby
files.delete_many
PHP
files->deleteMany
Go
Files.DeleteMany
Java
files().deleteMany
CLI
openemail files delete-many