Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """Support for the Mailgun mail notifications."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from pymailgunner import (
8  Client,
9  MailgunCredentialsError,
10  MailgunDomainError,
11  MailgunError,
12 )
13 import voluptuous as vol
14 
16  ATTR_DATA,
17  ATTR_TITLE,
18  ATTR_TITLE_DEFAULT,
19  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
20  BaseNotificationService,
21 )
22 from homeassistant.const import CONF_API_KEY, CONF_DOMAIN, CONF_RECIPIENT, CONF_SENDER
23 from homeassistant.core import HomeAssistant
24 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
25 
26 from . import CONF_SANDBOX, DOMAIN as MAILGUN_DOMAIN
27 
28 _LOGGER = logging.getLogger(__name__)
29 
30 # Images to attach to notification
31 ATTR_IMAGES = "images"
32 
33 DEFAULT_SANDBOX = False
34 
35 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
36  {vol.Required(CONF_RECIPIENT): vol.Email(), vol.Optional(CONF_SENDER): vol.Email()}
37 )
38 
39 
41  hass: HomeAssistant,
42  config: ConfigType,
43  discovery_info: DiscoveryInfoType | None = None,
44 ) -> MailgunNotificationService | None:
45  """Get the Mailgun notification service."""
46  data = hass.data[MAILGUN_DOMAIN]
47  mailgun_service = MailgunNotificationService(
48  data.get(CONF_DOMAIN),
49  data.get(CONF_SANDBOX),
50  data.get(CONF_API_KEY),
51  config.get(CONF_SENDER),
52  config.get(CONF_RECIPIENT),
53  )
54  if mailgun_service.connection_is_valid():
55  return mailgun_service
56 
57  return None
58 
59 
60 class MailgunNotificationService(BaseNotificationService):
61  """Implement a notification service for the Mailgun mail service."""
62 
63  def __init__(self, domain, sandbox, api_key, sender, recipient):
64  """Initialize the service."""
65  self._client_client = None # Mailgun API client
66  self._domain_domain = domain
67  self._sandbox_sandbox = sandbox
68  self._api_key_api_key = api_key
69  self._sender_sender = sender
70  self._recipient_recipient = recipient
71 
72  def initialize_client(self):
73  """Initialize the connection to Mailgun."""
74 
75  self._client_client = Client(self._api_key_api_key, self._domain_domain, self._sandbox_sandbox)
76  _LOGGER.debug("Mailgun domain: %s", self._client_client.domain)
77  self._domain_domain = self._client_client.domain
78  if not self._sender_sender:
79  self._sender_sender = f"hass@{self._domain}"
80 
82  """Check whether the provided credentials are valid."""
83 
84  try:
85  self.initialize_clientinitialize_client()
86  except MailgunCredentialsError:
87  _LOGGER.exception("Invalid credentials")
88  return False
89  except MailgunDomainError:
90  _LOGGER.exception("Unexpected exception")
91  return False
92  return True
93 
94  def send_message(self, message="", **kwargs):
95  """Send a mail to the recipient."""
96 
97  subject = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
98  data = kwargs.get(ATTR_DATA)
99  files = data.get(ATTR_IMAGES) if data else None
100 
101  try:
102  # Initialize the client in case it was not.
103  if self._client_client is None:
104  self.initialize_clientinitialize_client()
105  resp = self._client_client.send_mail(
106  sender=self._sender_sender,
107  to=self._recipient_recipient,
108  subject=subject,
109  text=message,
110  files=files,
111  )
112  _LOGGER.debug("Message sent: %s", resp)
113  except MailgunError:
114  _LOGGER.exception("Failed to send message")
def __init__(self, domain, sandbox, api_key, sender, recipient)
Definition: notify.py:63
MailgunNotificationService|None get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:44