Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add tasks for sending the emails via sendgrid API

Maciej Korycinskid908a7f1184d
diff --git a/saleor/plugins/sengrid/__init__.py b/saleor/plugins/sendgrid/__init__.py
similarity index 90%
rename from saleor/plugins/sengrid/__init__.py
rename to saleor/plugins/sendgrid/__init__.py
index 493e72bbf2..caa317d7f9 100644
--- a/saleor/plugins/sengrid/__init__.py
+++ b/saleor/plugins/sendgrid/__init__.py
@@ -3,8 +3,10 @@ from typing import Optional
@dataclass
-class SengridConfiguration:
+class SendgridConfiguration:
api_key: Optional[str]
+ sender_name: Optional[str]
+ sender_address: Optional[str]
account_confirmation_template_id: Optional[str]
account_set_customer_password_template_id: Optional[str]
account_delete_template_id: Optional[str]
diff --git a/saleor/plugins/sengrid/plugin.py b/saleor/plugins/sendgrid/plugin.py
similarity index 51%
rename from saleor/plugins/sengrid/plugin.py
rename to saleor/plugins/sendgrid/plugin.py
index fc309e2863..0780afb138 100644
--- a/saleor/plugins/sengrid/plugin.py
+++ b/saleor/plugins/sendgrid/plugin.py
@@ -1,14 +1,99 @@
-from ...core.notify_events import NotifyEventType
+import logging
+from dataclasses import asdict
+
+from ...core.notify_events import NotifyEventType, UserNotifyEvent
from ..base_plugin import BasePlugin, ConfigurationTypeField
-from . import SengridConfiguration
+from . import SendgridConfiguration
+from .tasks import (
+ send_account_confirmation_email_task,
+ send_account_delete_confirmation_email_task,
+ send_fulfillment_confirmation_email_task,
+ send_fulfillment_update_email_task,
+ send_invoice_email_task,
+ send_order_canceled_email_task,
+ send_order_confirmation_email_task,
+ send_order_confirmed_email_task,
+ send_order_refund_email_task,
+ send_password_reset_email_task,
+ send_payment_confirmation_email_task,
+ send_request_email_change_email_task,
+ send_set_user_password_email_task,
+ send_user_change_email_notification_task,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def get_event_to_task_map():
+ return {
+ UserNotifyEvent.ACCOUNT_CONFIRMATION: send_account_confirmation_email_task,
+ UserNotifyEvent.ACCOUNT_SET_CUSTOMER_PASSWORD: (
+ send_set_user_password_email_task
+ ),
+ UserNotifyEvent.ACCOUNT_DELETE: send_account_delete_confirmation_email_task,
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM: (
+ send_user_change_email_notification_task
+ ),
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST: (
+ send_request_email_change_email_task
+ ),
+ UserNotifyEvent.ACCOUNT_PASSWORD_RESET: send_password_reset_email_task,
+ UserNotifyEvent.INVOICE_READY: send_invoice_email_task,
+ UserNotifyEvent.ORDER_CONFIRMATION: send_order_confirmation_email_task,
+ UserNotifyEvent.ORDER_CONFIRMED: send_order_confirmed_email_task,
+ UserNotifyEvent.ORDER_FULFILLMENT_CONFIRMATION: (
+ send_fulfillment_confirmation_email_task
+ ),
+ UserNotifyEvent.ORDER_FULFILLMENT_UPDATE: send_fulfillment_update_email_task,
+ UserNotifyEvent.ORDER_PAYMENT_CONFIRMATION: (
+ send_payment_confirmation_email_task
+ ),
+ UserNotifyEvent.ORDER_CANCELED: send_order_canceled_email_task,
+ UserNotifyEvent.ORDER_REFUND_CONFIRMATION: send_order_refund_email_task,
+ }
-class SengridEmailPlugin(BasePlugin):
- PLUGIN_ID = "mirumee.notifications.sengrid_email"
- PLUGIN_NAME = "Sengrid"
+def get_dynamic_template_map():
+ return {
+ UserNotifyEvent.ACCOUNT_CONFIRMATION: "account_confirmation_template_id",
+ UserNotifyEvent.ACCOUNT_SET_CUSTOMER_PASSWORD: (
+ "account_set_customer_password_template_id"
+ ),
+ UserNotifyEvent.ACCOUNT_DELETE: "account_delete_template_id",
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM: (
+ "account_change_email_confirm_template_id"
+ ),
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST: (
+ "account_change_email_request_template_id"
+ ),
+ UserNotifyEvent.ACCOUNT_PASSWORD_RESET: "account_password_reset_template_id",
+ UserNotifyEvent.INVOICE_READY: "invoice_ready_template_id",
+ UserNotifyEvent.ORDER_CONFIRMATION: "order_confirmation_template_id",
+ UserNotifyEvent.ORDER_CONFIRMED: "order_confirmed_template_id",
+ UserNotifyEvent.ORDER_FULFILLMENT_CONFIRMATION: (
+ "order_fulfillment_confirmation_template_id"
+ ),
+ UserNotifyEvent.ORDER_FULFILLMENT_UPDATE: (
+ "order_fulfillment_update_template_id"
+ ),
+ UserNotifyEvent.ORDER_PAYMENT_CONFIRMATION: (
+ "order_payment_confirmation_template_id"
+ ),
+ UserNotifyEvent.ORDER_CANCELED: "order_canceled_template_id",
+ UserNotifyEvent.ORDER_REFUND_CONFIRMATION: (
+ "order_refund_confirmation_template_id"
+ ),
+ }
+
+
+class SendgridEmailPlugin(BasePlugin):
+ PLUGIN_ID = "mirumee.notifications.sendgrid_email"
+ PLUGIN_NAME = "Sendgrid"
DEFAULT_ACTIVE = False
DEFAULT_CONFIGURATION = [
+ {"name": "sender_name", "value": ""},
+ {"name": "sender_address", "value": ""},
{"name": "account_confirmation_template_id", "value": None},
{"name": "account_set_customer_password_template_id", "value": None},
{"name": "account_delete_template_id", "value": None},
@@ -26,6 +111,16 @@ class SengridEmailPlugin(BasePlugin):
{"name": "api_key", "value": None},
]
CONFIG_STRUCTURE = {
+ "sender_name": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "Name which will be visible as 'from' name.",
+ "label": "Sender name",
+ },
+ "sender_address": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "Sender email which will be visible as 'from' email.",
+ "label": "Sender email",
+ },
"account_confirmation_template_id": {
"type": ConfigurationTypeField.STRING,
"help_text": "The dynamic template ID for account confirmation.",
@@ -111,19 +206,28 @@ class SengridEmailPlugin(BasePlugin):
super().__init__(*args, **kwargs)
# Convert to dict to easier take config elements
configuration = {item["name"]: item["value"] for item in self.configuration}
- self.config = SengridConfiguration(**configuration)
+ self.config = SendgridConfiguration(**configuration)
def notify(self, event: NotifyEventType, payload: dict, previous_value):
if not self.active:
return previous_value
- # event_map = get_admin_event_map()
- # if event not in AdminNotifyEvent.CHOICES:
- # return previous_value
- # if event not in event_map:
- # logger.warning(f"Missing handler for event {event}")
- # return previous_value
- # template_map = get_admin_template_map(self.templates)
- # if not template_map.get(event):
- # return previous_value
- # event_map[event](payload, asdict(self.config)) # type: ignore
+ if event not in UserNotifyEvent.CHOICES:
+ return previous_value
+
+ event_to_task_map = get_event_to_task_map()
+ if event not in event_to_task_map:
+ logger.warning(f"Missing handler for event {event}")
+ return previous_value
+
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ event_to_template_fields = get_dynamic_template_map()
+ template_id = configuration.get(event_to_template_fields.get(event))
+
+ if not template_id:
+ # the empty fields means that we should not send an email for this event.
+ return previous_value
+
+ event_to_task_map[event].delay(payload, asdict(self.config))
+
+ # FIXME validation of the provided plugin data
diff --git a/saleor/plugins/sendgrid/tasks.py b/saleor/plugins/sendgrid/tasks.py
new file mode 100644
index 0000000000..9d84cf24d1
--- /dev/null
+++ b/saleor/plugins/sendgrid/tasks.py
@@ -0,0 +1,287 @@
+import logging
+
+from sendgrid import SendGridAPIClient, SendGridException
+from sendgrid.helpers.mail import Mail
+
+from ...account import events as account_events
+from ...celeryconf import app
+from ...invoice import events as invoice_events
+from ...order import events as order_events
+from . import SendgridConfiguration
+
+logger = logging.getLogger(__name__)
+
+
+def send_email(configuration: SendgridConfiguration, template_id, payload):
+ recipient_email = payload["recipient_email"]
+ sendgrid_client = SendGridAPIClient(configuration.api_key)
+ from_email = (configuration.sender_address, configuration.sender_name)
+ message = Mail(from_email=from_email, to_emails=recipient_email)
+ message.dynamic_template_data = payload
+ message.template_id = template_id
+ sendgrid_client.send(message)
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_account_confirmation_email_task(payload: dict, configuration: dict):
+ print(configuration)
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.account_confirmation_template_id,
+ payload=payload,
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_password_reset_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ user_id = payload.get("user", {}).get("id")
+ send_email(
+ configuration=configuration,
+ template_id=configuration.account_password_reset_template_id,
+ payload=payload,
+ )
+ account_events.customer_password_reset_link_sent_event(user_id=user_id)
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_request_email_change_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ user_id = payload.get("user", {}).get("id")
+ send_email(
+ configuration=configuration,
+ template_id=configuration.account_change_email_request_template_id,
+ payload=payload,
+ )
+ account_events.customer_email_change_request_event(
+ user_id=user_id,
+ parameters={
+ "old_email": payload.get("old_email"),
+ "new_email": payload["recipient_email"],
+ },
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_user_change_email_notification_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ user_id = payload.get("user", {}).get("id")
+ send_email(
+ configuration=configuration,
+ template_id=configuration.account_change_email_confirm_template_id,
+ payload=payload,
+ )
+ event_parameters = {
+ "old_email": payload["old_email"],
+ "new_email": payload["new_email"],
+ }
+
+ account_events.customer_email_changed_event(
+ user_id=user_id, parameters=event_parameters
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_account_delete_confirmation_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.account_delete_template_id,
+ payload=payload,
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_set_user_password_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.account_set_customer_password_template_id,
+ payload=payload,
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_invoice_email_task(payload: dict, configuration: dict):
+ """Send an invoice to user of related order with URL to download it."""
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.invoice_ready_template_id,
+ payload=payload,
+ )
+ invoice_events.notification_invoice_sent_event(
+ user_id=payload["requester_user_id"],
+ invoice_id=payload["invoice"]["id"],
+ customer_email=payload["recipient_email"],
+ )
+ order_events.event_invoice_sent_notification(
+ order_id=payload["invoice"]["order_id"],
+ user_id=payload["requester_user_id"],
+ email=payload["recipient_email"],
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_order_confirmation_email_task(payload: dict, configuration: dict):
+ """Send order confirmation email."""
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.order_confirmation_template_id,
+ payload=payload,
+ )
+ order_events.event_order_confirmation_notification(
+ order_id=payload["order"]["id"],
+ user_id=payload["order"].get("user_id"),
+ customer_email=payload["recipient_email"],
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_fulfillment_confirmation_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.order_fulfillment_confirmation_template_id,
+ payload=payload,
+ )
+ order_events.event_fulfillment_confirmed_notification(
+ order_id=payload["order"]["id"],
+ user_id=payload["requester_user_id"],
+ customer_email=payload["recipient_email"],
+ )
+
+ if payload.get("digital_lines"):
+ order_events.event_fulfillment_digital_links_notification(
+ order_id=payload["order"]["id"],
+ user_id=payload["requester_user_id"],
+ customer_email=payload["recipient_email"],
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_fulfillment_update_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.order_fulfillment_update_template_id,
+ payload=payload,
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_payment_confirmation_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.order_payment_confirmation_template_id,
+ payload=payload,
+ )
+ order_events.event_payment_confirmed_notification(
+ order_id=payload["order"]["id"],
+ user_id=payload["order"].get("user_id"),
+ customer_email=payload["recipient_email"],
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_order_canceled_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.order_canceled_template_id,
+ payload=payload,
+ )
+ order_events.event_order_cancelled_notification(
+ order_id=payload["order"]["id"],
+ user_id=payload["requester_user_id"],
+ customer_email=payload["recipient_email"],
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_order_refund_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.order_refund_confirmation_template_id,
+ payload=payload,
+ )
+ order_events.event_order_refunded_notification(
+ order_id=payload["order"]["id"],
+ user_id=payload["requester_user_id"],
+ customer_email=payload["recipient_email"],
+ )
+
+
+ autoretry_for=(SendGridException,),
+ retry_backoff=60,
+ retry_kwargs={"max_retries": 5},
+)
+def send_order_confirmed_email_task(payload: dict, configuration: dict):
+ configuration = SendgridConfiguration(**configuration)
+ send_email(
+ configuration=configuration,
+ template_id=configuration.order_confirmed_template_id,
+ payload=payload,
+ )
+ order_events.event_order_confirmed_notification(
+ order_id=payload.get("order", {}).get("id"),
+ user_id=payload.get("requester_user_id"),
+ customer_email=payload["recipient_email"],
+ )
diff --git a/saleor/plugins/sengrid/tasks.py b/saleor/plugins/sengrid/tasks.py
deleted file mode 100644
index adb2386f9d..0000000000
--- a/saleor/plugins/sengrid/tasks.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from sendgrid import SendGridAPIClient
-from sendgrid.helpers.mail import Mail
-
-from ...celeryconf import app
-from . import SengridConfiguration
-
-
-def send_email_task(configuration: SengridConfiguration, email_event, payload):
- sengrid_client = SendGridAPIClient(configuration.api_key)
diff --git a/saleor/settings.py b/saleor/settings.py
index 2b13280f8e..91ea5af5ac 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -524,6 +524,7 @@ PLUGINS = [
"saleor.plugins.invoicing.plugin.InvoicingPlugin",
"saleor.plugins.user_email.plugin.UserEmailPlugin",
"saleor.plugins.admin_email.plugin.AdminEmailPlugin",
+ "saleor.plugins.sendgrid.plugin.SendgridEmailPlugin",
]
# Plugin discovery