Home Assistant Unofficial Reference 2024.12.1
notify.py
Go to the documentation of this file.
1 """SendGrid notification service."""
2 
3 from __future__ import annotations
4 
5 from http import HTTPStatus
6 import logging
7 
8 from sendgrid import SendGridAPIClient
9 import voluptuous as vol
10 
12  ATTR_TITLE,
13  ATTR_TITLE_DEFAULT,
14  PLATFORM_SCHEMA as NOTIFY_PLATFORM_SCHEMA,
15  BaseNotificationService,
16 )
17 from homeassistant.const import (
18  CONF_API_KEY,
19  CONF_RECIPIENT,
20  CONF_SENDER,
21  CONTENT_TYPE_TEXT_PLAIN,
22 )
23 from homeassistant.core import HomeAssistant
25 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
26 
27 _LOGGER = logging.getLogger(__name__)
28 
29 CONF_SENDER_NAME = "sender_name"
30 
31 DEFAULT_SENDER_NAME = "Home Assistant"
32 
33 PLATFORM_SCHEMA = NOTIFY_PLATFORM_SCHEMA.extend(
34  {
35  vol.Required(CONF_API_KEY): cv.string,
36  vol.Required(CONF_SENDER): vol.Email(),
37  vol.Required(CONF_RECIPIENT): vol.Email(),
38  vol.Optional(CONF_SENDER_NAME, default=DEFAULT_SENDER_NAME): cv.string,
39  }
40 )
41 
42 
44  hass: HomeAssistant,
45  config: ConfigType,
46  discovery_info: DiscoveryInfoType | None = None,
47 ) -> SendgridNotificationService:
48  """Get the SendGrid notification service."""
49  return SendgridNotificationService(config)
50 
51 
52 class SendgridNotificationService(BaseNotificationService):
53  """Implementation the notification service for email via Sendgrid."""
54 
55  def __init__(self, config):
56  """Initialize the service."""
57  self.api_keyapi_key = config[CONF_API_KEY]
58  self.sendersender = config[CONF_SENDER]
59  self.sender_namesender_name = config[CONF_SENDER_NAME]
60  self.recipientrecipient = config[CONF_RECIPIENT]
61 
62  self._sg_sg = SendGridAPIClient(self.api_keyapi_key)
63 
64  def send_message(self, message="", **kwargs):
65  """Send an email to a user via SendGrid."""
66  subject = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
67 
68  data = {
69  "personalizations": [
70  {"to": [{"email": self.recipientrecipient}], "subject": subject}
71  ],
72  "from": {"email": self.sendersender, "name": self.sender_namesender_name},
73  "content": [{"type": CONTENT_TYPE_TEXT_PLAIN, "value": message}],
74  }
75 
76  response = self._sg_sg.client.mail.send.post(request_body=data)
77  if response.status_code != HTTPStatus.ACCEPTED:
78  _LOGGER.error("Unable to send notification")
SendgridNotificationService get_service(HomeAssistant hass, ConfigType config, DiscoveryInfoType|None discovery_info=None)
Definition: notify.py:47