airflow.providers.microsoft.azure.hooks.msgraph

This module contains a Microsoft Graph API hook and the email backend built on it.

Attributes

PaginationCallable

Classes

CachedAsyncTokenCredential

Wraps an async Azure credential to prevent kiota from closing it after each token request.

DefaultResponseHandler

DefaultResponseHandler returns JSON payload or content in bytes or response headers.

KiotaRequestAdapterHook

A Microsoft Graph API interaction hook, a Wrapper around KiotaRequestAdapter.

MSGraphMailHook

Send mail from an Office 365 mailbox through the Microsoft Graph sendMail endpoint.

Functions

execute_callable(func, *args, **kwargs)

Dynamically call a function by matching its signature to provided args/kwargs.

send_email(to, subject, html_content[, files, dryrun, ...])

Email backend for Microsoft Graph.

Module Contents

airflow.providers.microsoft.azure.hooks.msgraph.PaginationCallable[source]
airflow.providers.microsoft.azure.hooks.msgraph.execute_callable(func, *args, **kwargs)[source]

Dynamically call a function by matching its signature to provided args/kwargs.

class airflow.providers.microsoft.azure.hooks.msgraph.CachedAsyncTokenCredential(credential)[source]

Bases: azure.core.credentials_async.AsyncTokenCredential

Wraps an async Azure credential to prevent kiota from closing it after each token request.

kiota_authentication_azure calls await credential.close() after every successful get_token call (see AzureIdentityAccessTokenProvider.get_authorization_token). That tears down the underlying AioHttpTransport session so the next request fails with “HTTP transport has already been closed”. Suppressing close() keeps the session alive for the lifetime of the cached RequestAdapter.

property closed: bool[source]
async __aenter__()[source]

Return self upon entering the runtime context.

async __aexit__(exc_type=None, exc_value=None, traceback=None)[source]

Raise any exception triggered within the runtime context.

async get_token(*args, **kwargs)[source]

Request an access token for scopes.

Parameters:
  • scopes (str) – The type of access needed.

  • claims (str) – Additional claims required in the token, such as those returned in a resource provider’s claims challenge following an authorization failure.

  • tenant_id (str) – Optional tenant to include in the token request.

  • enable_cae (bool) – Indicates whether to enable Continuous Access Evaluation (CAE) for the requested token. Defaults to False.

Return type:

AccessToken

Returns:

An AccessToken instance containing the token string and its expiration time in Unix time.

async get_token_info(*args, **kwargs)[source]
async close()[source]

Intentionally a no-op — the credential session is closed when the adapter is evicted.

class airflow.providers.microsoft.azure.hooks.msgraph.DefaultResponseHandler[source]

Bases: kiota_abstractions.response_handler.ResponseHandler

DefaultResponseHandler returns JSON payload or content in bytes or response headers.

static get_value(response)[source]
async handle_response_async(response, error_map)[source]

Invoke this callback method when a response is received.

param response: The type of the native response object. param error_map: The error dict to use in case of a failed request.

class airflow.providers.microsoft.azure.hooks.msgraph.KiotaRequestAdapterHook(conn_id=default_conn_name, timeout=None, proxies=None, host=None, scopes=None, api_version=None)[source]

Bases: airflow.providers.common.compat.sdk.BaseHook

A Microsoft Graph API interaction hook, a Wrapper around KiotaRequestAdapter.

https://github.com/microsoftgraph/msgraph-sdk-python-core

Parameters:
  • conn_id (str) – The HTTP Connection ID to run the trigger against.

  • timeout (float | None) – The HTTP timeout being used by the KiotaRequestAdapter (default is None). When no timeout is specified or set to None then no HTTP timeout is applied on each request.

  • proxies (dict | None) – A Dict defining the HTTP proxies to be used (default is None).

  • host (str | None) – The host to be used (default is “https://graph.microsoft.com”).

  • scopes (str | list[str] | None) – The scopes to be used (default is [”https://graph.microsoft.com/.default”]).

  • api_version (msgraph_core.APIVersion | str | None) – The API version of the Microsoft Graph API to be used (default is v1). You can pass an enum named APIVersion which has 2 possible members v1 and beta, or you can pass a string as “v1.0” or “beta”.

DEFAULT_HEADERS[source]
DEFAULT_SCOPE = 'https://graph.microsoft.com/.default'[source]
cached_request_adapters: dict[str, tuple[str, kiota_abstractions.request_adapter.RequestAdapter]][source]
conn_type: str = 'msgraph'[source]
conn_name_attr: str = 'conn_id'[source]
default_conn_name: str = 'msgraph_default'[source]
hook_name: str = 'Microsoft Graph API'[source]
conn_id = 'msgraph_default'[source]
timeout = None[source]
proxies = None[source]
host = None[source]
api_version[source]
allowed_netloc: str | None = None[source]
classmethod get_connection_form_widgets()[source]

Return connection widgets to add to connection form.

classmethod get_ui_field_behaviour()[source]

Return custom field behaviour.

static resolve_api_version_from_value(api_version, default=None)[source]
get_api_version(config)[source]
get_host(connection)[source]
get_base_url(host, api_version, config)[source]
static format_no_proxy_url(url)[source]
classmethod to_httpx_proxies(proxies)[source]
to_msal_proxies(authority, proxies)[source]
static get_allowed_hosts(authority, config)[source]
get_conn()[source]

Initiate a new RequestAdapter connection.

Warning

This method is deprecated. Use get_async_conn() instead.

async get_async_conn()[source]

Initiate a new RequestAdapter connection asynchronously.

get_proxies(config)[source]
get_credentials(login, password, config, authority, verify, proxies)[source]
test_connection()[source]

Test HTTP Connection.

static default_pagination(response, url=None, query_parameters=None, responses=lambda : ...)[source]

Resolve the url and query parameters of the page following response.

The $skip offset is derived from query_parameters rather than from responses: callers accumulate whatever their own callbacks produced, so the entries are not guaranteed to be the raw pages this offset would have to be counted from.

async run(url='', response_type=None, path_parameters=None, method='GET', query_parameters=None, headers=None, data=None)[source]
async get_allowed_netlocs()[source]

Return the endpoint’s host and the connection’s allowed hosts, for checking pagination links.

async assert_allowed_host(url)[source]

Refuse an absolute url whose host the connection does not allow.

A pagination link (e.g. @odata.nextLink) is echoed from the API response and is re-fetched with the connection’s bearer token attached. That token is withheld only from hosts outside allowed_hosts, which defaults to empty (any host) unless configured, so a tampered response could send it to an arbitrary host (CWE-918).

async paginated_run(url='', response_type=None, path_parameters=None, method='GET', query_parameters=None, headers=None, data=None, pagination_function=None)[source]
async send_request(request_info, response_type=None)[source]
async close()[source]

Close the request adapter cached for this connection and evict it from the cache.

request_information(url, response_type=None, path_parameters=None, method='GET', query_parameters=None, headers=None, data=None)[source]
static normalize_url(url)[source]
static encoded_query_parameters(query_parameters)[source]
static error_mapping()[source]
class airflow.providers.microsoft.azure.hooks.msgraph.MSGraphMailHook(conn_id=default_conn_name, timeout=None, proxies=None, host=None, scopes=None, api_version=None)[source]

Bases: KiotaRequestAdapterHook

Send mail from an Office 365 mailbox through the Microsoft Graph sendMail endpoint.

The application registration behind the connection needs the Mail.Send permission, and with application permissions an administrator has to grant it access to the sending mailbox.

https://learn.microsoft.com/en-us/graph/api/user-sendmail

Parameters:
  • conn_id (str) – The Microsoft Graph API connection id.

  • timeout (float | None) – The HTTP timeout being used by the KiotaRequestAdapter (default is None). When no timeout is specified or set to None then no HTTP timeout is applied on each request.

  • proxies (dict | None) – A Dict defining the HTTP proxies to be used (default is None).

  • host (str | None) – The host to be used (default is “https://graph.microsoft.com”).

  • scopes (str | list[str] | None) – The scopes to be used (default is [”https://graph.microsoft.com/.default”]).

  • api_version (msgraph_core.APIVersion | str | None) – The API version of the Microsoft Graph API to be used (default is v1).

MAX_ATTACHMENTS_SIZE = 3145728[source]
static extract_email_addresses(addresses)[source]

Split a comma or semicolon separated string, or an iterable, into a list of addresses.

static extract_sender(from_email)[source]

Extract the bare address of the mailbox to send from.

classmethod build_recipients(addresses)[source]

Build the Microsoft Graph recipient representation for the given addresses.

classmethod build_attachments(files)[source]

Read each file from disk and build its Microsoft Graph fileAttachment representation.

classmethod build_message(to, subject, html_content, files=None, cc=None, bcc=None, custom_headers=None)[source]

Build the Microsoft Graph message body for the given email fields.

async asend_email(from_email, to, subject, html_content, files=None, cc=None, bcc=None, custom_headers=None, save_to_sent_items=True, dryrun=False)[source]

Send an email from the from_email mailbox (async).

Parameters:
  • from_email (str) – The mailbox the message is sent from.

  • to (str | collections.abc.Iterable[str]) – Recipient email address or list of addresses.

  • subject (str) – Email subject.

  • html_content (str) – Email body in HTML format.

  • files (collections.abc.Iterable[str] | None) – List of file paths to attach to the email.

  • cc (str | collections.abc.Iterable[str] | None) – Carbon copy recipient email address or list of addresses.

  • bcc (str | collections.abc.Iterable[str] | None) – Blind carbon copy recipient email address or list of addresses.

  • custom_headers (dict[str, Any] | None) – Custom internet message headers, whose names have to start with “x-“.

  • save_to_sent_items (bool) – Whether the message is saved in the mailbox’s Sent Items folder.

  • dryrun (bool) – If True, the message is prepared but not sent.

send_email(from_email, to, subject, html_content, files=None, cc=None, bcc=None, custom_headers=None, save_to_sent_items=True, dryrun=False)[source]

Send an email from the from_email mailbox.

Parameters:
  • from_email (str) – The mailbox the message is sent from.

  • to (str | collections.abc.Iterable[str]) – Recipient email address or list of addresses.

  • subject (str) – Email subject.

  • html_content (str) – Email body in HTML format.

  • files (collections.abc.Iterable[str] | None) – List of file paths to attach to the email.

  • cc (str | collections.abc.Iterable[str] | None) – Carbon copy recipient email address or list of addresses.

  • bcc (str | collections.abc.Iterable[str] | None) – Blind carbon copy recipient email address or list of addresses.

  • custom_headers (dict[str, Any] | None) – Custom internet message headers, whose names have to start with “x-“.

  • save_to_sent_items (bool) – Whether the message is saved in the mailbox’s Sent Items folder.

  • dryrun (bool) – If True, the message is prepared but not sent.

airflow.providers.microsoft.azure.hooks.msgraph.send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', mime_charset='utf-8', conn_id=None, from_email=None, custom_headers=None, **kwargs)[source]

Email backend for Microsoft Graph.

Note

For more information, see Send email using Microsoft Graph

Was this entry helpful?