문서로 건너뛰기
Python

openemail.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.list()

List one page of the files the mailbox holds

범위files:read결과를 페이지 단위로 가져옴
시그니처
def list(    *,    limit: int | None = None,    cursor: str | None = None,    q: str | None = None,    kind: FileKind | None = None,    direction: FileDirection | None = None,    address: str | None = None,    since: datetime | str | None = None,    until: datetime | str | None = None,    sort: FileSort | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> Page[FileResource]

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. list_all 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.list_attachments reads them.

매개변수

limitint

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

cursorstr

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

qstr

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

kindFileKind

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

directionFileDirection

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.

addressstr

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

sincedatetime | str

Keeps files added at or after this moment. A datetime or an ISO 8601 string.

untildatetime | str

Keeps files added before this moment. A datetime or an ISO 8601 string.

sortFileSort

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

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

Page[FileResource], a dict with items, hasMore and nextCursor. Each item has id, filename, mimeType, sizeBytes, direction, threadId, messageId, deliveredTo, usage, deletable, visibility, publicUrl and createdAt.

예시

from openemail import openemail page = openemail.files.list(kind='pdf', sort='largest') for file in page['items']:    print(file['filename'], file['sizeBytes'], file['usage'] or 'deletable') print(page['hasMore'], page['nextCursor'])

참고

  • 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()
Ruby
files.list
CLI
openemail files list

files.list_all()

Collect every file into one list

범위files:read결과를 페이지 단위로 가져옴
시그니처
def list_all(    *,    limit: int | None = None,    cursor: str | None = None,    q: str | None = None,    kind: FileKind | None = None,    direction: FileDirection | None = None,    address: str | None = None,    since: datetime | str | None = None,    until: datetime | str | None = None,    sort: FileSort | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> builtins.list[FileResource]

Walks every page of list and returns every file in one list, in the order sort= names. One request per page, with the same filters on each.

매개변수

limitint

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

cursorstr

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

qstr

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

kindFileKind

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

directionFileDirection

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.

addressstr

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

sincedatetime | str

Keeps files added at or after this moment. A datetime or an ISO 8601 string.

untildatetime | str

Keeps files added before this moment. A datetime or an ISO 8601 string.

sortFileSort

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

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

list[FileResource] holding every file.

예시

from openemail import openemail invoices = openemail.files.list_all(q='invoice', direction='inbound') total = sum(file['sizeBytes'] for file in invoices)print(len(invoices), 'invoices received,', total, 'bytes in all')

참고

  • If any page fails the call raises, and the rows already fetched are discarded.

다른 사용처

API
GET /files
TypeScript
files.listAll()
Ruby
files.list_all

files.iterate()

Stream the files one at a time

범위files:read결과를 페이지 단위로 가져옴
시그니처
def iterate(    *,    limit: int | None = None,    cursor: str | None = None,    q: str | None = None,    kind: FileKind | None = None,    direction: FileDirection | None = None,    address: str | None = None,    since: datetime | str | None = None,    until: datetime | str | None = None,    sort: FileSort | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> Iterator[FileResource]

Returns a generator 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 leaving the loop with break stops the requests.

매개변수

limitint

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

cursorstr

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

qstr

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

kindFileKind

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

directionFileDirection

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.

addressstr

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

sincedatetime | str

Keeps files added at or after this moment. A datetime or an ISO 8601 string.

untildatetime | str

Keeps files added before this moment. A datetime or an ISO 8601 string.

sortFileSort

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

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

Iterator[FileResource], a generator yielding one file per step.

예시

from openemail import openemail for file in openemail.files.iterate(sort='oldest'):    print(file['createdAt'], file['filename'], file['deliveredTo'])

참고

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

다른 사용처

API
GET /files
TypeScript
files.iterate()
Ruby
files.iterate

files.get()

Read one file by id

범위files:read
시그니처
def get(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> FileResource

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

매개변수

idstr필수

The id from list, file_ and 24 hex.

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

FileResource, with usage and deletable. visibility is public while a download link to it works, and publicUrl is then one of those links.

예시

from openemail import openemail file = openemail.files.get('file_6bb640f5b99e47deb758f1f5') print(file['filename'], file['mimeType'], file['deletable'])

참고

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

다른 사용처

API
GET /files/{id}
TypeScript
files.get()
Ruby
files.get
CLI
openemail files get

files.stats()

Count the files and the space they take

범위files:read
시그니처
def stats(    *,    api_key: str | None = None,    timeout: float | None = None,) -> 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.

매개변수

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

FileStatsResource with totals, received, sent and uploaded, each a dict with files and bytes, then types, byDay, addresses and links.

예시

from openemail import openemail stats = openemail.files.stats() print(stats['totals']['files'], 'files in', stats['totals']['bytes'], 'bytes') for kind in stats['types']:    print(kind['mimeType'], kind['files'], kind['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 None when none was ever fetched. Scanners and link previewers are left out of the count.

다른 사용처

API
GET /files/stats
TypeScript
files.stats()
Ruby
files.stats
CLI
openemail files stats

files.download()

Fetch the bytes of a file

범위files:read
시그니처
def download(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> bytes

Returns the file exactly as it is stored, the same bytes the Download action on the Files page saves. The server sends it with the file's own Content-Type and name, but the method returns only the bytes, so read the name and the type from get.

매개변수

idstr필수

The id from list.

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

bytes holding the file.

예시

from pathlib import Path from openemail import openemail file = openemail.files.get('file_6bb640f5b99e47deb758f1f5')data = openemail.files.download(file['id']) name = Path(file['filename']).namePath(name).write_bytes(data)print('Saved', name, len(data), 'bytes')

참고

  • 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()
Ruby
files.download
CLI
openemail files download

files.upload()

Upload a file to the Files page

범위files:write
시그니처
def upload(    data: RawBody,    *,    filename: str,    content_type: str | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> FileResource

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 None and deletable is True. Attach it to a send as {'fileId': file['id']} in emails.send, which is how a file larger than the inline cap goes out.

data is bytes, a bytearray or a memoryview, 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 content_type=, 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 None, so a narrowed key never reaches that file afterwards.

매개변수

dataRawBody필수

The file as bytes, a bytearray or a memoryview, not empty and at most 100 MB.

filenamestr필수

The name the file is stored and downloaded under, such as report.pdf. A blank name raises ValueError before anything is sent.

content_typestr

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

api_keystr

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

timeoutfloat

Seconds the upload may take, the response included, before it raises OpenEmailNetworkError with is_timeout. Left out, it is 600 seconds, or the client's timeout when that is longer, and no limit at all when the client's timeout is 0. 0 turns the limit off for this call.

반환값

FileResource for the new file, with direction set to 'uploaded', usage set to None and deletable set to True.

예시

from pathlib import Path from openemail import openemail file = openemail.files.upload(    Path('invoice.pdf').read_bytes(), filename='invoice.pdf', content_type='application/pdf') openemail.emails.send(    {        'from': '[email protected]',        'to': '[email protected]',        'subject': 'Your September invoice',        'text': 'The invoice is attached.',        'attachments': [{'fileId': file['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 list 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()
Ruby
files.upload
CLI
openemail files upload

files.delete()

Delete an uploaded file for good

범위files:write
시그니처
def delete(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> 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.

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

매개변수

idstr필수

The id from list.

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

DeletedFileResource, such as {'object': 'file', 'id': 'file_6bb640f5b99e47deb758f1f5', 'deleted': True}.

예시

from openemail import OpenEmailApiError, openemail try:    removed = openemail.files.delete('file_6bb640f5b99e47deb758f1f5')    print(removed['id'], removed['deleted'])except OpenEmailApiError as error:    if error.is_not_found:        print('Already deleted')    elif error.code == 'file_in_use':        print(error.message)    else:        raise

참고

  • 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' on the error, and its usage on get 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()
Ruby
files.delete
CLI
openemail files delete

files.delete_many()

Delete up to 100 files in one call

범위files:write
시그니처
def delete_many(    ids: Sequence[str],    *,    api_key: str | None = None,    timeout: float | None = None,) -> 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.

매개변수

idsSequence[str]필수

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

api_keystr

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

timeoutfloat

Seconds this call may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It overrides the client's timeout for this call, and 0 turns the limit off.

반환값

FileBatchDeleteResource with object set to 'file_batch_delete', deleted, kept and missing. deleted and missing are lists of ids, and each entry of kept is a dict with id, filename, usage and reason.

예시

from openemail import openemail result = openemail.files.delete_many(    ['file_6bb640f5b99e47deb758f1f5', 'file_0c3e2a91d4b7f6058e1a2b3c']) print(len(result['deleted']), 'deleted,', len(result['missing']), 'missing') for kept in result['kept']:    print(kept['filename'], kept['reason'])

참고

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

  • A partial result returns rather than raises, 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 list_all whose deletable is True and pass their ids 100 at a time.

다른 사용처

API
POST /files/batch-delete
TypeScript
files.deleteMany()
Ruby
files.delete_many
CLI
openemail files delete-many