core/homeassistant/components/sendgrid/notify.py

71 lines
2.1 KiB
Python
Raw Normal View History

"""SendGrid notification service."""
2016-02-27 21:44:39 +00:00
import logging
from sendgrid import SendGridAPIClient
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_TITLE,
ATTR_TITLE_DEFAULT,
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.const import (
2019-07-31 19:25:30 +00:00
CONF_API_KEY,
CONF_RECIPIENT,
CONF_SENDER,
CONTENT_TYPE_TEXT_PLAIN,
HTTP_ACCEPTED,
2019-07-31 19:25:30 +00:00
)
import homeassistant.helpers.config_validation as cv
2016-02-27 21:44:39 +00:00
_LOGGER = logging.getLogger(__name__)
2016-02-27 21:44:39 +00:00
2019-07-31 19:25:30 +00:00
CONF_SENDER_NAME = "sender_name"
2019-07-31 19:25:30 +00:00
DEFAULT_SENDER_NAME = "Home Assistant"
# pylint: disable=no-value-for-parameter
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_SENDER): vol.Email(),
vol.Required(CONF_RECIPIENT): vol.Email(),
vol.Optional(CONF_SENDER_NAME, default=DEFAULT_SENDER_NAME): cv.string,
}
)
def get_service(hass, config, discovery_info=None):
2016-03-08 10:46:32 +00:00
"""Get the SendGrid notification service."""
return SendgridNotificationService(config)
2016-02-27 21:44:39 +00:00
class SendgridNotificationService(BaseNotificationService):
2016-07-23 17:51:20 +00:00
"""Implementation the notification service for email via Sendgrid."""
2016-02-27 21:44:39 +00:00
def __init__(self, config):
2016-03-08 10:46:32 +00:00
"""Initialize the service."""
self.api_key = config[CONF_API_KEY]
self.sender = config[CONF_SENDER]
self.sender_name = config[CONF_SENDER_NAME]
self.recipient = config[CONF_RECIPIENT]
2016-02-27 21:44:39 +00:00
2019-05-06 12:13:16 +00:00
self._sg = SendGridAPIClient(self.api_key)
2016-02-27 21:44:39 +00:00
2019-07-31 19:25:30 +00:00
def send_message(self, message="", **kwargs):
2016-03-08 10:46:32 +00:00
"""Send an email to a user via SendGrid."""
subject = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
2016-02-27 21:44:39 +00:00
2016-07-23 17:51:20 +00:00
data = {
"personalizations": [
2019-07-31 19:25:30 +00:00
{"to": [{"email": self.recipient}], "subject": subject}
2016-07-23 17:51:20 +00:00
],
2019-07-31 19:25:30 +00:00
"from": {"email": self.sender, "name": self.sender_name},
"content": [{"type": CONTENT_TYPE_TEXT_PLAIN, "value": message}],
2016-07-23 17:51:20 +00:00
}
response = self._sg.client.mail.send.post(request_body=data)
if response.status_code != HTTP_ACCEPTED:
_LOGGER.error("Unable to send notification")