Saltar para a documentação
Python

openemail.imports

Cada método deste espaço de nomes: a sua assinatura, os seus parâmetros, o que devolve e um exemplo.

Métodos

Bring an old mailbox across from a Google Takeout, .mbox, .eml, .zip or .tgz export, with progress and a list of what did not come through.

imports.list()

List one page of mailbox imports

Âmbitosthreads:readPercorre os resultados por páginas
Assinatura
def list(    *,    limit: int | None = None,    cursor: str | None = None,    address_id: str | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> Page[ImportResource]

Returns one page of the imports in the workspace, newest first. Nothing is dropped from the history, so following nextCursor while hasMore is True reaches the very first import, and list_all and iterate do that walk for you. Each carries its status, the bytes read so far out of the total, and running counts of messages seen, imported, skipped as duplicates, left out by your options and not imported.

A key limited to particular addresses sees only imports into those addresses.

Parâmetros

limitint

Rows per page, a whole number from 1 to 100. The server defaults to 25.

cursorstr

The nextCursor from the previous page, an import id. One that names no import this key can see is a 400 invalid_cursor.

address_idstr

Only imports into the address with this id.

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.

Devolve

Page[ImportResource], a dict with items, hasMore and nextCursor.

Exemplo

from openemail import openemail page = openemail.imports.list(limit=50) for item in page['items']:    print(item['address'], item['status'], item['counts']['imported'])

Notas

  • A GET is retried automatically on network failure and on 408, 429 and 5xx responses, up to the client's max_retries.

Também disponível em

API
GET /imports
TypeScript
imports.list()
Ruby
imports.list
CLI
openemail imports list

imports.list_all()

Collect every mailbox import into one list

Âmbitosthreads:readPercorre os resultados por páginas
Assinatura
def list_all(    *,    limit: int | None = None,    cursor: str | None = None,    address_id: str | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> builtins.list[ImportResource]

Follows nextCursor from page to page and returns every import in the workspace as one list, newest first, narrowed to one address when address_id= is given. A key limited to particular addresses sees only imports into those addresses.

Parâmetros

limitint

Page size per request, from 1 to 100, defaulting to 25 on the server.

cursorstr

An import id to start after, skipping everything newer.

address_idstr

Only imports into the address with this id.

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.

Devolve

list[ImportResource] holding every import across all pages.

Exemplo

from openemail import openemail imports = openemail.imports.list_all()failed = [item for item in imports if item['status'] == 'failed'] print(f'{len(failed)} of {len(imports)} imports failed')

Notas

  • A failure on any page makes the whole call raise, and the imports already fetched are discarded.

Também disponível em

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

imports.iterate()

Stream mailbox imports one at a time

Âmbitosthreads:readPercorre os resultados por páginas
Assinatura
def iterate(    *,    limit: int | None = None,    cursor: str | None = None,    address_id: str | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> Iterator[ImportResource]

Returns a generator that yields imports one at a time, newest first, and requests the next page only once the current one is used up. Nothing is fetched until you start iterating, and breaking out of the loop stops the requests.

Parâmetros

limitint

Page size per request, from 1 to 100, defaulting to 25 on the server.

cursorstr

An import id to start after, skipping everything newer.

address_idstr

Only imports into the address with this id.

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.

Devolve

Iterator[ImportResource], a generator yielding one import per step.

Exemplo

from openemail import openemail for item in openemail.imports.iterate(address_id='7c9d2e41-0b8f-4a63-9e25-1f4d6a8b3c70'):    if item['status'] == 'running':        print(item['id'], item['counts']['imported'])        break

Notas

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

Também disponível em

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

imports.get()

Read one mailbox import

Âmbitosthreads:read
Assinatura
def get(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportResource

Returns one import with its status, byte progress and counts. Poll it while status is queued or running. It settles on completed, failed or cancelled.

An id from another workspace answers exactly like one that never existed, with 404.

Parâmetros

idstrObrigatório

Import id, imp_ followed by 24 hex characters.

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.

Devolve

ImportResource.

Exemplo

from openemail import openemail item = openemail.imports.get('imp_3f9c2a7b1e4d8f60a5c7b92d') print(item['status'], item['processedBytes'], '/', item['totalBytes'])

Notas

  • lastError is set only when status is failed.

Também disponível em

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

imports.create()

Create a mailbox import and get its upload plan

Âmbitosthreads:write
Assinatura
def create(    body: ImportCreate,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportResource

Creates an import into one address of the workspace and returns it with status set to uploading. Each file is uploaded through upload_chunk in parts of chunkBytes, as many as its entry in files gives in chunks, and start then queues the import.

The import reads Google Takeout archives, .mbox files from Apple Mail, Thunderbird and most desktop apps, .eml files, and .zip or .tgz archives holding any of those, up to 100 GB a file and 50 files an import. Threads, dates and labels come across. Imported mail is quiet: it runs no rules, forwards, notifications, summaries or webhooks.

import_files does create, upload and start in one call.

Parâmetros

body['addressId']strObrigatório

The id of the address the mail belongs to. It must be an address this workspace owns and this key may act for.

body['files']list[ImportFileDescriptor]Obrigatório

Each file as a dict of its name and its size in bytes, such as {'name': 'takeout-001.zip', 'bytes': 2147483648}, 1 to 50 of them, each at most 100 GB.

body['options']['keepInbox']bool

Defaults to True: mail that was in the old inbox lands in Inbox with its unread state. False files everything under Archive.

body['options']['includeSpam']bool

True brings the mail in the old spam folder across too, into Spam. Defaults to False, which leaves it out.

body['options']['includeTrash']bool

True brings the mail in the old trash across too, into the Bin. Defaults to False, which leaves it out.

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.

Devolve

ImportResource with status set to uploading, chunkBytes, and each file's chunks in files.

Exemplo

from pathlib import Path from openemail import openemail archive = Path('archive.zip')item = openemail.imports.create(    {        'addressId': '7c9d2e41-0b8f-4a63-9e25-1f4d6a8b3c70',        'files': [{'name': 'takeout-001.zip', 'bytes': archive.stat().st_size}],        'options': {'keepInbox': False, 'includeTrash': True},    }) print(item['id'], item['chunkBytes'], item['files'][0]['chunks'])

Notas

  • An address with an import already queued or running is 409 already_running.

  • Not retried automatically by the SDK.

Também disponível em

API
POST /imports
TypeScript
imports.create()
Ruby
imports.create
CLI
openemail imports create

imports.upload_state()

See which parts of the upload have arrived

Âmbitosthreads:write
Assinatura
def upload_state(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportUploadResource

For each file, the indexes of the parts already stored, so an interrupted upload sends only what is missing. Empty once the import has left the uploading state.

Parâmetros

idstrObrigatório

Import id, imp_ followed by 24 hex characters.

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.

Devolve

ImportUploadResource with received, one sorted list of part indexes per file.

Exemplo

from openemail import openemail state = openemail.imports.upload_state('imp_3f9c2a7b1e4d8f60a5c7b92d') for file, parts in enumerate(state['received']):    print(f'file {file}: {len(parts)} parts stored')

Também disponível em

API
GET /imports/{id}/upload
TypeScript
imports.uploadState()
Ruby
imports.upload_state
CLI
openemail imports upload-state

imports.upload_chunk()

Upload one part of an import file

Âmbitosthreads:write
Assinatura
def upload_chunk(    id: str,    file: int,    chunk: int,    data: RawBody,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportChunkResource

Stores one part of file file: the bytes from chunk * chunkBytes up to the next part. Every part is exactly chunkBytes long except the last, and a part of the wrong length is 400 bad_chunk. Sending a part again replaces it, so a failed part can simply be retried.

Parâmetros

idstrObrigatório

Import id, imp_ followed by 24 hex characters.

fileintObrigatório

The file index, in the order given to create.

chunkintObrigatório

The part index, from 0.

dataRawBodyObrigatório

The part as bytes, bytearray or memoryview.

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.

Devolve

ImportChunkResource echoing file, chunk and the bytes stored.

Exemplo

from pathlib import Path from openemail import openemail content = Path('mailbox.mbox').read_bytes()item = openemail.imports.create(    {        'addressId': '7c9d2e41-0b8f-4a63-9e25-1f4d6a8b3c70',        'files': [{'name': 'mailbox.mbox', 'bytes': len(content)}],    })size = item['chunkBytes'] for chunk in range(item['files'][0]['chunks']):    part = content[chunk * size : (chunk + 1) * size]    stored = openemail.imports.upload_chunk(item['id'], 0, chunk, part)    print(stored['chunk'], stored['bytes'])

Notas

  • Retried automatically on network failure and on 408, 429 and 5xx responses, since a repeated part replaces itself.

Também disponível em

API
PUT /imports/{id}/files/{file}/chunks/{chunk}
TypeScript
imports.uploadChunk()
Ruby
imports.upload_chunk
CLI
openemail imports upload-chunk

imports.start()

Queue an import once its files are uploaded

Âmbitosthreads:write
Assinatura
def start(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportResource

Checks that every part of every file has arrived, recognises each file's format and queues the import. A file still missing parts is 412 missing_chunks, and a file that is not an archive or a mailbox is 400 unsupported_file. Calling it on an import that has already left uploading returns it unchanged.

Parâmetros

idstrObrigatório

Import id, imp_ followed by 24 hex characters.

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.

Devolve

ImportResource with status set to queued.

Exemplo

from openemail import OpenEmailApiError, openemail try:    queued = openemail.imports.start('imp_3f9c2a7b1e4d8f60a5c7b92d')except OpenEmailApiError as error:    if error.code != 'missing_chunks':        raise    print(error.message)else:    print(queued['status'], queued['formats'])

Notas

  • Retried automatically on network failure and on 408, 429 and 5xx responses, since starting an import that already started returns it unchanged.

Também disponível em

API
POST /imports/{id}/start
TypeScript
imports.start()
Ruby
imports.start
CLI
openemail imports start

imports.cancel()

Cancel a mailbox import

Âmbitosthreads:write
Assinatura
def cancel(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportResource

Stops an import at its next checkpoint. Mail already imported stays in the mailbox. A finished import is 409 not_cancellable.

Parâmetros

idstrObrigatório

Import id, imp_ followed by 24 hex characters.

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.

Devolve

ImportResource with status set to cancelled.

Exemplo

from openemail import openemail item = openemail.imports.cancel('imp_3f9c2a7b1e4d8f60a5c7b92d') print(item['status'], item['counts']['imported'], 'messages kept')

Também disponível em

API
POST /imports/{id}/cancel
TypeScript
imports.cancel()
Ruby
imports.cancel
CLI
openemail imports cancel

imports.list_failures()

List what an import could not bring across

Âmbitosthreads:read
Assinatura
def list_failures(    id: str,    *,    after: int | None = None,    limit: int | None = None,    api_key: str | None = None,    timeout: float | None = None,) -> ImportFailurePage

Each message or archive entry that did not come across, with the reason: too-large (over 50 MB), unparseable, no-date, storage-error, unreadable-entry, encrypted-entry or archive-limit. Page with after=, passing the nextCursor of the previous page.

Parâmetros

idstrObrigatório

Import id, imp_ followed by 24 hex characters.

afterint

The nextCursor of the previous page.

limitint

At most 100, the default.

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.

Devolve

ImportFailurePage with the failures in data and nextCursor, an int while more follow and None on the last page.

Exemplo

from openemail import openemail page = openemail.imports.list_failures('imp_3f9c2a7b1e4d8f60a5c7b92d', limit=100) for failure in page['data']:    print(failure['reason'], failure['subject'], failure['detail']) if page['nextCursor'] is not None:    more = openemail.imports.list_failures(        'imp_3f9c2a7b1e4d8f60a5c7b92d', after=page['nextCursor'], limit=100    )    print(len(more['data']), 'more on the next page')

Também disponível em

API
GET /imports/{id}/failures
TypeScript
imports.listFailures()
Ruby
imports.list_failures
CLI
openemail imports list-failures

imports.delete_upload()

Delete the files uploaded for an import

Âmbitosthreads:write
Assinatura
def delete_upload(    id: str,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportResource

Removes the uploaded archive. Mail already imported stays in the mailbox. An import still uploading is cancelled at the same time, and one that is queued or running is 409 still_running.

Parâmetros

idstrObrigatório

Import id, imp_ followed by 24 hex characters.

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.

Devolve

ImportResource with uploadDeleted set to True.

Exemplo

from openemail import openemail item = openemail.imports.delete_upload('imp_3f9c2a7b1e4d8f60a5c7b92d') print(item['uploadDeleted'], item['status'])

Também disponível em

API
DELETE /imports/{id}/upload
TypeScript
imports.deleteUpload()
Ruby
imports.delete_upload
CLI
openemail imports delete-upload

imports.import_files()

Create, upload and start an import in one call

Âmbitosthreads:write
Assinatura
def import_files(    input: ImportFilesInput,    *,    api_key: str | None = None,    timeout: float | None = None,) -> ImportResource

Creates the import, uploads every file part by part and starts it, calling onProgress after each part. Pass each file's content as bytes, bytearray or memoryview. Parts are sliced from it without copying the whole file, so a memoryview of an mmap over the file on disk keeps a large archive out of memory.

It returns once the import is queued. Poll get to follow it.

Parâmetros

input['addressId']strObrigatório

The id of the address the mail belongs to.

input['files']list[ImportSource]Obrigatório

Each file as a dict of its name and its content in data, such as {'name': 'takeout-001.zip', 'data': content}.

input['options']ImportOptions

keepInbox, includeSpam and includeTrash, as for create.

input['onProgress']ImportProgress

A function called after each part with two ints: the bytes uploaded so far and the total.

api_keystr

Overrides the client's API key for every request this call makes.

timeoutfloat

Seconds each of its requests may take, the response included, before it raises OpenEmailNetworkError with is_timeout. It limits the create, every part and the start one at a time, not the upload as a whole. It overrides the client's timeout, and 0 turns the limit off.

Devolve

ImportResource with status set to queued.

Exemplo

from pathlib import Path from openemail import openemail item = openemail.imports.import_files(    {        'addressId': '7c9d2e41-0b8f-4a63-9e25-1f4d6a8b3c70',        'files': [{'name': 'takeout-001.zip', 'data': Path('archive.zip').read_bytes()}],        'onProgress': lambda done, total: print(f'{done} of {total} bytes uploaded'),    }) print(item['id'], item['status'])

Notas

  • If a part still fails after its retries, the call raises and the import is left in uploading. upload_state then says which parts to send before calling start.

Também disponível em

API
POST /imports
TypeScript
imports.importFiles()
Ruby
imports.import_files
CLI
openemail imports import-files