Skip to content

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

Plugin interface - add fields for configuring smtp server (#6444)

Maciej Korycinskif79ffe476c1c
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index 1c1cb17527..035be791e8 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -17,7 +17,7 @@ if TYPE_CHECKING:
def get_order_line_payload(line: "OrderLine"):
- unit_tax_amount = (line.unit_price_gross_amount - line.unit_price_net_amount,)
+ unit_tax_amount = line.unit_price_gross_amount - line.unit_price_net_amount
total_gross = line.unit_price_gross * line.quantity
total_net = line.unit_price_net * line.quantity
total_tax = total_gross - total_net
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index b3fd1773a5..2f5cc548d7 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -17,7 +17,7 @@ from ..utils import add_variant_to_draft_order
def test_get_order_line_payload(order_line):
payload = get_order_line_payload(order_line)
unit_tax_amount = (
- order_line.unit_price_gross_amount - order_line.unit_price_net_amount,
+ order_line.unit_price_gross_amount - order_line.unit_price_net_amount
)
total_gross = order_line.unit_price_gross * order_line.quantity
total_net = order_line.unit_price_net * order_line.quantity
diff --git a/saleor/plugins/admin_email/notify_events.py b/saleor/plugins/admin_email/notify_events.py
new file mode 100644
index 0000000000..d3b85f831d
--- /dev/null
+++ b/saleor/plugins/admin_email/notify_events.py
@@ -0,0 +1,31 @@
+from .tasks import (
+ send_email_with_link_to_download_file_task,
+ send_export_failed_email_task,
+ send_set_staff_password_email_task,
+ send_staff_order_confirmation_email_task,
+)
+
+
+def send_set_staff_password_email(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ send_set_staff_password_email_task.delay(
+ recipient_email, payload["redirect_url"], payload["token"], config
+ )
+
+
+def send_csv_product_export_success(payload: dict, config: dict):
+ recipient_email = payload.get("recipient_email")
+ if recipient_email:
+ send_email_with_link_to_download_file_task.delay(
+ recipient_email, payload["csv_link"], config
+ )
+
+
+def send_staff_order_confirmation(payload: dict, config: dict):
+ send_staff_order_confirmation_email_task.delay(payload, config)
+
+
+def send_csv_export_failed(payload: dict, config: dict):
+ recipient_email = payload.get("recipient_email")
+ if recipient_email:
+ send_export_failed_email_task.delay(recipient_email, config)
diff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.py
index 4b2ff6ff87..6c69822f18 100644
--- a/saleor/plugins/admin_email/plugin.py
+++ b/saleor/plugins/admin_email/plugin.py
@@ -1,61 +1,72 @@
import logging
-from dataclasses import dataclass
+from dataclasses import asdict
+
+from django.conf import settings
from ...core.notify_events import AdminNotifyEvent, NotifyEventType
from ..base_plugin import BasePlugin
-from . import emails
+from ..email_common import (
+ DEFAULT_EMAIL_CONFIG_STRUCTURE,
+ DEFAULT_EMAIL_CONFIGURATION,
+ EmailConfig,
+ validate_default_email_configuration,
+)
+from ..models import PluginConfiguration
+from .notify_events import (
+ send_csv_export_failed,
+ send_csv_product_export_success,
+ send_set_staff_password_email,
+ send_staff_order_confirmation,
+)
logger = logging.getLogger(__name__)
-@dataclass
-class UserEmailConfig:
- account_confirmation_template: str
- account_password_reset_template: str
-
-
-event_map = {
- AdminNotifyEvent.STAFF_ORDER_CONFIRMATION: emails.send_staff_order_confirmation,
- AdminNotifyEvent.ACCOUNT_SET_STAFF_PASSWORD: emails.send_set_staff_password_email,
- AdminNotifyEvent.CSV_PRODUCT_EXPORT_SUCCESS: emails.send_csv_product_export_success,
- AdminNotifyEvent.CSV_EXPORT_FAILED: emails.send_csv_export_failed,
-}
+def get_admin_event_map():
+ return {
+ AdminNotifyEvent.STAFF_ORDER_CONFIRMATION: send_staff_order_confirmation,
+ AdminNotifyEvent.ACCOUNT_SET_STAFF_PASSWORD: send_set_staff_password_email,
+ AdminNotifyEvent.CSV_PRODUCT_EXPORT_SUCCESS: send_csv_product_export_success,
+ AdminNotifyEvent.CSV_EXPORT_FAILED: send_csv_export_failed,
+ }
class AdminEmailPlugin(BasePlugin):
PLUGIN_ID = "mirumee.notifications.admin_email"
PLUGIN_NAME = "Admin emails"
+ DEFAULT_ACTIVE = True
+
+ DEFAULT_CONFIGURATION = [] + DEFAULT_EMAIL_CONFIGURATION # type: ignore
+ CONFIG_STRUCTURE = {}
+ CONFIG_STRUCTURE.update(DEFAULT_EMAIL_CONFIG_STRUCTURE)
- # TODO the configuration will be implemented in separate pull request
-
- # DEFAULT_CONFIGURATION = [
- # {"name": "account-confirmation_template", "value": None},
- # {"name": "account-password-reset-template", "value": None},
- # ]
- #
- # CONFIG_STRUCTURE = {
- # "account-confirmation_template": {
- # "type": ConfigurationTypeField.SECRET,
- # "help_text": "",
- # "label": "Account confirmation template",
- # },
- # "account-password-reset-template": {
- # "type": ConfigurationTypeField.SECRET,
- # "help_text": "",
- # "label": "Account password reset template",
- # },
- # }
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- # configuration = {item["name"]: item["value"] for item in self.configuration}
- self.active = True
+
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = EmailConfig(
+ host=configuration["host"] or settings.EMAIL_HOST,
+ port=configuration["port"] or settings.EMAIL_PORT,
+ username=configuration["username"] or settings.EMAIL_HOST_USER,
+ password=configuration["password"] or settings.EMAIL_HOST_PASSWORD,
+ sender_name=configuration["sender_name"],
+ sender_address=configuration["sender_address"],
+ use_tls=configuration["use_tls"],
+ use_ssl=configuration["use_ssl"],
+ )
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
- event_map[event](payload) # type: ignore
+ event_map[event](payload, asdict(self.config)) # type: ignore
+
+ @classmethod
+ def validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):
+ """Validate if provided configuration is correct."""
+ validate_default_email_configuration(plugin_configuration)
diff --git a/saleor/plugins/admin_email/tasks.py b/saleor/plugins/admin_email/tasks.py
index 84e9701611..3684c58a82 100644
--- a/saleor/plugins/admin_email/tasks.py
+++ b/saleor/plugins/admin_email/tasks.py
@@ -1,60 +1,67 @@
from urllib.parse import urlencode
-from templated_email import send_templated_mail
-
from ...celeryconf import app
from ...core.emails import get_email_context
from ...core.utils.url import prepare_url
+from ..email_common import EmailConfig, send_email
@app.task
-def send_set_staff_password_email_task(recipient_email, redirect_url, token):
+def send_set_staff_password_email_task(
+ recipient_email, redirect_url, token, config: dict
+):
+ email_config = EmailConfig(**config)
params = urlencode({"email": recipient_email, "token": token})
password_set_url = prepare_url(params, redirect_url)
- _send_set_password_email(recipient_email, password_set_url)
+ _send_set_password_email(recipient_email, password_set_url, email_config)
-def _send_set_password_email(recipient_email, password_set_url):
+def _send_set_password_email(recipient_email, password_set_url, config: EmailConfig):
send_kwargs, ctx = get_email_context()
ctx["password_set_url"] = password_set_url
- send_templated_mail(
- template_name="dashboard/staff/set_password",
+ send_email(
+ config=config,
recipient_list=[recipient_email],
+ template_name="dashboard/staff/set_password",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_email_with_link_to_download_file_task(recipient_email: str, csv_link: str):
+def send_email_with_link_to_download_file_task(
+ recipient_email: str, csv_link: str, config: dict
+):
+ email_config = EmailConfig(**config)
send_kwargs, ctx = get_email_context()
ctx["csv_link"] = csv_link
- send_templated_mail(
- template_name="csv/export_products_file",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="csv/export_products_file",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_export_failed_email_task(recipient_email: str):
+def send_export_failed_email_task(recipient_email: str, config: dict):
+ email_config = EmailConfig(**config)
send_kwargs, ctx = get_email_context()
- send_templated_mail(
- template_name="csv/export_failed",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="csv/export_failed",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_staff_order_confirmation_email_task(payload):
+def send_staff_order_confirmation_email_task(payload, config: dict):
+ email_config = EmailConfig(**config)
send_kwargs, ctx = get_email_context()
payload.update(ctx)
- send_templated_mail(
- template_name="order/staff_confirm_order",
+ send_email(
+ config=email_config,
recipient_list=payload["recipient_list"],
- context=payload,
- **send_kwargs,
+ template_name="order/staff_confirm_order",
+ context=ctx,
)
diff --git a/saleor/plugins/admin_email/tests/conftest.py b/saleor/plugins/admin_email/tests/conftest.py
new file mode 100644
index 0000000000..d52e7525ad
--- /dev/null
+++ b/saleor/plugins/admin_email/tests/conftest.py
@@ -0,0 +1,46 @@
+from unittest.mock import patch
+
+import pytest
+
+from ...manager import get_plugins_manager
+from ..plugin import AdminEmailPlugin
+
+
+def admin_email_plugin(settings):
+ def fun(
+ host="localhost",
+ port="1025",
+ username=None,
+ password=None,
+ sender_name="Admin Name",
+ sender_address="[email protected]",
+ use_tls=False,
+ use_ssl=False,
+ active=True,
+ ):
+ settings.PLUGINS = ["saleor.plugins.admin_email.plugin.AdminEmailPlugin"]
+ manager = get_plugins_manager()
+ with patch(
+ "saleor.plugins.admin_email.plugin.validate_default_email_configuration"
+ ):
+ manager.save_plugin_configuration(
+ AdminEmailPlugin.PLUGIN_ID,
+ {
+ "active": active,
+ "configuration": [
+ {"name": "host", "value": host},
+ {"name": "port", "value": port},
+ {"name": "username", "value": username},
+ {"name": "password", "value": password},
+ {"name": "sender_name", "value": sender_name},
+ {"name": "sender_address", "value": sender_address},
+ {"name": "use_tls", "value": use_tls},
+ {"name": "use_ssl", "value": use_ssl},
+ ],
+ },
+ )
+ manager = get_plugins_manager()
+ return manager.plugins[0]
+
+ return fun
diff --git a/saleor/plugins/admin_email/tests/test_plugin.py b/saleor/plugins/admin_email/tests/test_plugin.py
new file mode 100644
index 0000000000..7347af6f0a
--- /dev/null
+++ b/saleor/plugins/admin_email/tests/test_plugin.py
@@ -0,0 +1,147 @@
+from dataclasses import asdict
+from smtplib import SMTPNotSupportedError
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+from django.core.exceptions import ValidationError
+from django.core.mail.backends.smtp import EmailBackend
+
+from ....core.notify_events import NotifyEventType
+from ...models import PluginConfiguration
+from ..notify_events import (
+ send_csv_export_failed,
+ send_csv_product_export_success,
+ send_set_staff_password_email,
+ send_staff_order_confirmation,
+)
+from ..plugin import get_admin_event_map
+
+
+def test_event_map():
+ assert get_admin_event_map() == {
+ NotifyEventType.STAFF_ORDER_CONFIRMATION: send_staff_order_confirmation,
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD: send_set_staff_password_email,
+ NotifyEventType.CSV_PRODUCT_EXPORT_SUCCESS: send_csv_product_export_success,
+ NotifyEventType.CSV_EXPORT_FAILED: send_csv_export_failed,
+ }
+
+
+ "event_type",
+ [
+ NotifyEventType.STAFF_ORDER_CONFIRMATION,
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD,
+ NotifyEventType.CSV_PRODUCT_EXPORT_SUCCESS,
+ NotifyEventType.CSV_EXPORT_FAILED,
+ ],
+)
+@patch("saleor.plugins.admin_email.plugin.get_admin_event_map")
+def test_notify(mocked_get_event_map, event_type, admin_email_plugin):
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+ mocked_event = Mock()
+ mocked_get_event_map.return_value = {event_type: mocked_event}
+
+ plugin = admin_email_plugin()
+ plugin.notify(event_type, payload, previous_value=None)
+
+ mocked_event.assert_called_with(payload, asdict(plugin.config))
+
+
+@patch("saleor.plugins.admin_email.plugin.get_admin_event_map")
+def test_notify_event_not_related(mocked_get_event_map, admin_email_plugin):
+ event_type = NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+
+ mocked_event = Mock()
+ mocked_get_event_map.return_value = {event_type: mocked_event}
+
+ plugin = admin_email_plugin()
+ plugin.notify(event_type, payload, previous_value=None)
+
+ assert not mocked_event.called
+
+
+@patch("saleor.plugins.admin_email.plugin.get_admin_event_map")
+def test_notify_event_missing_handler(mocked_get_event_map, admin_email_plugin):
+ event_type = NotifyEventType.CSV_EXPORT_FAILED
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+
+ mocked_event_map = MagicMock()
+ mocked_get_event_map.return_value = mocked_event_map
+
+ plugin = admin_email_plugin()
+ plugin.notify(event_type, payload, previous_value=None)
+
+ assert not mocked_event_map.__getitem__.called
+
+
+@patch("saleor.plugins.admin_email.plugin.get_admin_event_map")
+def test_notify_event_plugin_is_not_active(mocked_get_event_map, admin_email_plugin):
+ event_type = NotifyEventType.CSV_EXPORT_FAILED
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+
+ plugin = admin_email_plugin(active=False)
+ plugin.notify(event_type, payload, previous_value=None)
+
+ assert not mocked_get_event_map.called
+
+
+def test_save_plugin_configuration_tls_and_ssl_are_mutually_exclusive(
+ admin_email_plugin,
+):
+ plugin = admin_email_plugin()
+ configuration = PluginConfiguration.objects.get()
+ data_to_save = {
+ "configuration": [
+ {"name": "use_tls", "value": True},
+ {"name": "use_ssl", "value": True},
+ ]
+ }
+ with pytest.raises(ValidationError):
+ plugin.save_plugin_configuration(configuration, data_to_save)
+
+
[email protected](EmailBackend, "open")
+def test_save_plugin_configuration(mocked_open, admin_email_plugin):
+ plugin = admin_email_plugin()
+ configuration = PluginConfiguration.objects.get()
+ data_to_save = {
+ "configuration": [
+ {"name": "use_tls", "value": False},
+ {"name": "use_ssl", "value": True},
+ ]
+ }
+
+ plugin.save_plugin_configuration(configuration, data_to_save)
+
+ mocked_open.assert_called_with()
+
+
[email protected](EmailBackend, "open")
+def test_save_plugin_configuration_incorrect_email_backend_configuration(
+ mocked_open, admin_email_plugin
+):
+ plugin = admin_email_plugin()
+ mocked_open.side_effect = SMTPNotSupportedError()
+ configuration = PluginConfiguration.objects.get()
+ data_to_save = {
+ "configuration": [
+ {"name": "use_tls", "value": False},
+ {"name": "use_ssl", "value": True},
+ ]
+ }
+
+ with pytest.raises(ValidationError):
+ plugin.save_plugin_configuration(configuration, data_to_save)
diff --git a/saleor/plugins/admin_emails/__init__.py b/saleor/plugins/admin_emails/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/saleor/plugins/email_common.py b/saleor/plugins/email_common.py
new file mode 100644
index 0000000000..76813a4ce8
--- /dev/null
+++ b/saleor/plugins/email_common.py
@@ -0,0 +1,206 @@
+import logging
+from dataclasses import dataclass
+from email.headerregistry import Address
+from typing import Optional
+
+from django.conf import settings
+from django.contrib.sites.models import Site
+from django.core.exceptions import ValidationError
+from django.core.mail.backends.smtp import EmailBackend
+from templated_email import TemplateBackend
+
+from .base_plugin import ConfigurationTypeField
+from .error_codes import PluginErrorCode
+from .models import PluginConfiguration
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class EmailConfig:
+ host: Optional[str] = None
+ port: Optional[str] = None
+ username: Optional[str] = None
+ password: Optional[str] = None
+ sender_name: Optional[str] = None
+ sender_address: Optional[str] = None
+ use_tls: bool = False
+ use_ssl: bool = False
+
+
+DEFAULT_EMAIL_CONFIGURATION = [
+ {"name": "host", "value": None},
+ {"name": "port", "value": None},
+ {"name": "username", "value": None},
+ {"name": "password", "value": None},
+ {"name": "sender_name", "value": ""},
+ {"name": "sender_address", "value": ""},
+ {"name": "use_tls", "value": False},
+ {"name": "use_ssl", "value": False},
+]
+DEFAULT_EMAIL_CONFIG_STRUCTURE = {
+ "host": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "The host to use for sending email. Leave it blank if you want to use "
+ "system environment - EMAIL_HOST."
+ ),
+ "label": "SMTP host",
+ },
+ "port": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "Port to use for the SMTP server. Leave it blank if you want to use "
+ "system environment - EMAIL_PORT."
+ ),
+ "label": "SMTP port",
+ },
+ "username": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": (
+ "Username to use for the SMTP server. Leave it blank if you want to "
+ "use system environment - EMAIL_HOST_USER."
+ ),
+ "label": "SMTP user",
+ },
+ "password": {
+ "type": ConfigurationTypeField.PASSWORD,
+ "help_text": (
+ "Password to use for the SMTP server. Leave it blank if you want to "
+ "use system environment - EMAIL_HOST_PASSWORD."
+ ),
+ "label": "Password",
+ },
+ "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",
+ },
+ "use_tls": {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": (
+ "Whether to use a TLS (secure) connection when talking to the SMTP "
+ "server. This is used for explicit TLS connections, generally on port "
+ "587. Use TLS/Use SSL are mutually exclusive, so only set one of those"
+ " settings to True."
+ ),
+ "label": "Use TLS",
+ },
+ "use_ssl": {
+ "type": ConfigurationTypeField.BOOLEAN,
+ "help_text": (
+ "Whether to use an implicit TLS (secure) connection when talking to "
+ "the SMTP server. In most email documentation this type of TLS "
+ "connection is referred to as SSL. It is generally used on port 465. "
+ "Use TLS/Use SSL are mutually exclusive, so only set one of those"
+ " settings to True."
+ ),
+ "label": "Use SSL",
+ },
+}
+
+
+def send_email(config: EmailConfig, recipient_list, template_name, context):
+ sender_name = config.sender_name
+ sender_address = config.sender_address
+ if not sender_address or not sender_name:
+ # TODO when we deprecate the default mail config from Site, we can drop this if
+ # and require the sender's data as a plugin input.
+ site = Site.objects.get_current()
+ sender_name = sender_name or site.settings.default_mail_sender_name
+ sender_address = sender_address or site.settings.default_mail_sender_address
+ sender_address = sender_address or settings.DEFAULT_FROM_EMAIL
+
+ from_email = str(Address(sender_name, addr_spec=sender_address))
+ email_backend = EmailBackend(
+ host=config.host,
+ port=config.port,
+ username=config.username,
+ password=config.password,
+ use_ssl=config.use_ssl,
+ use_tls=config.use_tls,
+ )
+ template_backend = TemplateBackend()
+ template_backend.send(
+ from_email=from_email,
+ connection=email_backend,
+ template_name=template_name,
+ recipient_list=recipient_list,
+ context=context,
+ )
+ # TODO the template mail will be replaced by the send_mail whith rendered msg by
+ # staff user
+
+ # send_mail(
+ # subject,
+ # message,
+ # from_email,
+ # recipient_list,
+ # connection=email_backend
+ # )
+
+
+def validate_email_config(config: EmailConfig):
+ email_backend = EmailBackend(
+ host=config.host,
+ port=config.port,
+ username=config.username,
+ password=config.password,
+ use_ssl=config.use_ssl,
+ use_tls=config.use_tls,
+ fail_silently=False,
+ )
+ try:
+ email_backend.open()
+ except Exception:
+ raise
+ finally:
+ email_backend.close()
+
+
+def validate_default_email_configuration(plugin_configuration: "PluginConfiguration"):
+ """Validate if provided configuration is correct."""
+
+ configuration = plugin_configuration.configuration
+ configuration = {item["name"]: item["value"] for item in configuration}
+
+ if not plugin_configuration.active:
+ return
+
+ if configuration["use_tls"] and configuration["use_ssl"]:
+ error_msg = (
+ "Use TLS and Use SSL are mutually exclusive, so only set one of "
+ "those settings to True."
+ )
+ raise ValidationError(
+ {
+ "use_ssl": ValidationError(
+ error_msg, code=PluginErrorCode.INVALID.value,
+ ),
+ "use_tls": ValidationError(
+ error_msg, code=PluginErrorCode.INVALID.value,
+ ),
+ }
+ )
+ config = EmailConfig(**configuration)
+ try:
+ validate_email_config(config)
+ except Exception as e:
+ logger.warning("Unable to connect to email backend.", exc_info=e)
+ error_msg = (
+ "Unable to connect to email backend. Make sure that you provided "
+ "correct values."
+ )
+ raise ValidationError(
+ {
+ c: ValidationError(
+ error_msg, code=PluginErrorCode.PLUGIN_MISCONFIGURED.value
+ )
+ for c in configuration.keys()
+ }
+ )
diff --git a/saleor/plugins/user_email/notify_events.py b/saleor/plugins/user_email/notify_events.py
new file mode 100644
index 0000000000..ffaabb58a5
--- /dev/null
+++ b/saleor/plugins/user_email/notify_events.py
@@ -0,0 +1,100 @@
+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_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,
+)
+
+
+def send_account_password_reset_event(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ user_payload = payload["user"]
+ send_password_reset_email_task.delay(
+ recipient_email,
+ payload["redirect_url"],
+ user_payload["id"],
+ payload["token"],
+ config,
+ )
+
+
+def send_account_confirmation(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ send_account_confirmation_email_task.delay(
+ recipient_email, payload["token"], payload["redirect_url"], config
+ )
+
+
+def send_account_change_email_request(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ user_payload = payload["user"]
+ send_request_email_change_email_task.delay(
+ recipient_email,
+ payload["old_email"],
+ payload["redirect_url"],
+ user_payload["id"],
+ payload["token"],
+ config,
+ )
+
+
+def send_account_change_email_confirm(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ send_user_change_email_notification_task.delay(recipient_email, config)
+
+
+def send_account_delete(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ send_account_delete_confirmation_email_task.delay(
+ recipient_email, payload["redirect_url"], payload["token"], config
+ )
+
+
+def send_account_set_customer_password(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ send_set_user_password_email_task.delay(
+ recipient_email, payload["redirect_url"], payload["token"], config
+ )
+
+
+def send_invoice(payload: dict, config: dict):
+ recipient_email = payload["recipient_email"]
+ send_invoice_email_task.delay(
+ recipient_email=recipient_email,
+ invoice_number=payload["number"],
+ invoice_download_url=payload["download_url"],
+ config=config,
+ )
+
+
+def send_order_confirmation(payload: dict, config: dict):
+ send_order_confirmation_email_task(payload=payload, config=config)
+
+
+def send_fulfillment_confirmation(payload: dict, config: dict):
+ send_fulfillment_confirmation_email_task(payload, config)
+
+
+def send_fulfillment_update(payload: dict, config: dict):
+ send_fulfillment_update_email_task(payload, config)
+
+
+def send_payment_confirmation(payload: dict, config: dict):
+ send_payment_confirmation_email_task(payload, config)
+
+
+def send_order_canceled(payload: dict, config: dict):
+ send_order_canceled_email_task.delay(payload, config)
+
+
+def send_order_refund(payload: dict, config: dict):
+ send_order_refund_email_task.delay(payload, config)
diff --git a/saleor/plugins/user_email/plugin.py b/saleor/plugins/user_email/plugin.py
index 64b3083aa2..059e6a3168 100644
--- a/saleor/plugins/user_email/plugin.py
+++ b/saleor/plugins/user_email/plugin.py
@@ -1,9 +1,16 @@
import logging
-from dataclasses import dataclass
+from dataclasses import asdict
from ...core.notify_events import NotifyEventType, UserNotifyEvent
from ..base_plugin import BasePlugin
-from .emails import (
+from ..email_common import (
+ DEFAULT_EMAIL_CONFIG_STRUCTURE,
+ DEFAULT_EMAIL_CONFIGURATION,
+ EmailConfig,
+ validate_default_email_configuration,
+)
+from ..models import PluginConfiguration
+from .notify_events import (
send_account_change_email_confirm,
send_account_change_email_request,
send_account_confirmation,
@@ -22,27 +29,24 @@ from .emails import (
logger = logging.getLogger(__name__)
-@dataclass
-class UserEmailConfig:
- account_confirmation_template: str
- account_password_reset_template: str
-
-
-event_map = {
- UserNotifyEvent.ACCOUNT_CONFIRMATION: send_account_confirmation,
- UserNotifyEvent.ACCOUNT_SET_CUSTOMER_PASSWORD: send_account_set_customer_password,
- UserNotifyEvent.ACCOUNT_DELETE: send_account_delete,
- UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM: send_account_change_email_confirm,
- UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST: send_account_change_email_request,
- UserNotifyEvent.ACCOUNT_PASSWORD_RESET: send_account_password_reset_event,
- UserNotifyEvent.INVOICE_READY: send_invoice,
- UserNotifyEvent.ORDER_CONFIRMATION: send_order_confirmation,
- UserNotifyEvent.ORDER_FULFILLMENT_CONFIRMATION: send_fulfillment_confirmation,
- UserNotifyEvent.ORDER_FULFILLMENT_UPDATE: send_fulfillment_update,
- UserNotifyEvent.ORDER_PAYMENT_CONFIRMATION: send_payment_confirmation,
- UserNotifyEvent.ORDER_CANCELED: send_order_canceled,
- UserNotifyEvent.ORDER_REFUND_CONFIRMATION: send_order_refund,
-}
+def get_user_event_map():
+ return {
+ UserNotifyEvent.ACCOUNT_CONFIRMATION: send_account_confirmation,
+ UserNotifyEvent.ACCOUNT_SET_CUSTOMER_PASSWORD: (
+ send_account_set_customer_password
+ ),
+ UserNotifyEvent.ACCOUNT_DELETE: send_account_delete,
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM: send_account_change_email_confirm,
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST: send_account_change_email_request,
+ UserNotifyEvent.ACCOUNT_PASSWORD_RESET: send_account_password_reset_event,
+ UserNotifyEvent.INVOICE_READY: send_invoice,
+ UserNotifyEvent.ORDER_CONFIRMATION: send_order_confirmation,
+ UserNotifyEvent.ORDER_FULFILLMENT_CONFIRMATION: send_fulfillment_confirmation,
+ UserNotifyEvent.ORDER_FULFILLMENT_UPDATE: send_fulfillment_update,
+ UserNotifyEvent.ORDER_PAYMENT_CONFIRMATION: send_payment_confirmation,
+ UserNotifyEvent.ORDER_CANCELED: send_order_canceled,
+ UserNotifyEvent.ORDER_REFUND_CONFIRMATION: send_order_refund,
+ }
class UserEmailPlugin(BasePlugin):
@@ -50,35 +54,27 @@ class UserEmailPlugin(BasePlugin):
PLUGIN_NAME = "User emails"
# TODO the configuration will be implemented in separate pull request
- # DEFAULT_CONFIGURATION = [
- # {"name": "account-confirmation_template", "value": None},
- # {"name": "account-password-reset-template", "value": None},
- # ]
- #
- # CONFIG_STRUCTURE = {
- # "account-confirmation_template": {
- # "type": ConfigurationTypeField.SECRET,
- # "help_text": "",
- # "label": "Account confirmation template",
- # },
- # "account-password-reset-template": {
- # "type": ConfigurationTypeField.SECRET,
- # "help_text": "",
- # "label": "Account password reset template",
- # },
- # }
+ DEFAULT_CONFIGURATION = [] + DEFAULT_EMAIL_CONFIGURATION # type: ignore
+ CONFIG_STRUCTURE = {}
+ CONFIG_STRUCTURE.update(DEFAULT_EMAIL_CONFIG_STRUCTURE)
+
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- # configuration = {item["name"]: item["value"] for item in self.configuration}
- self.active = True
+ configuration = {item["name"]: item["value"] for item in self.configuration}
+ self.config = EmailConfig(**configuration)
def notify(self, event: NotifyEventType, payload: dict, previous_value):
if not self.active:
return previous_value
-
+ event_map = get_user_event_map()
if event not in UserNotifyEvent.CHOICES:
return previous_value
if event not in event_map:
logger.warning(f"Missing handler for event {event}")
return previous_value
- event_map[event](payload) # type: ignore
+ event_map[event](payload, asdict(self.config)) # type: ignore
+
+ @classmethod
+ def validate_plugin_configuration(cls, plugin_configuration: "PluginConfiguration"):
+ """Validate if provided configuration is correct."""
+ validate_default_email_configuration(plugin_configuration)
diff --git a/saleor/plugins/user_email/tasks.py b/saleor/plugins/user_email/tasks.py
index 36533c6755..15d6fc6f34 100644
--- a/saleor/plugins/user_email/tasks.py
+++ b/saleor/plugins/user_email/tasks.py
@@ -1,59 +1,63 @@
from urllib.parse import urlencode
-from templated_email import send_templated_mail
-
from ...account import events as account_events
from ...celeryconf import app
from ...core.emails import get_email_context
from ...core.utils.url import prepare_url
+from ..email_common import EmailConfig, send_email
@app.task
-def send_account_confirmation_email_task(email, token, redirect_url):
+def send_account_confirmation_email_task(email, token, redirect_url, config):
+ email_config = EmailConfig(**config)
params = urlencode({"email": email, "token": token})
confirm_url = prepare_url(params, redirect_url)
send_kwargs, ctx = get_email_context()
ctx["confirm_url"] = confirm_url
- send_templated_mail(
- template_name="account/confirm",
+ send_email(
+ config=email_config,
recipient_list=[email],
+ template_name="account/confirm",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_password_reset_email_task(recipient_email, redirect_url, user_id, token):
+def send_password_reset_email_task(
+ recipient_email, redirect_url, user_id, token, config
+):
+ email_config = EmailConfig(**config)
params = urlencode({"email": recipient_email, "token": token})
reset_url = prepare_url(params, redirect_url)
- _send_password_reset_email(recipient_email, reset_url, user_id)
+ _send_password_reset_email(recipient_email, reset_url, user_id, email_config)
-def _send_password_reset_email(recipient_email, reset_url, user_id):
+def _send_password_reset_email(recipient_email, reset_url, user_id, email_config):
send_kwargs, ctx = get_email_context()
ctx["reset_url"] = reset_url
- send_templated_mail(
- template_name="account/password_reset",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="account/password_reset",
context=ctx,
- **send_kwargs,
)
account_events.customer_password_reset_link_sent_event(user_id=user_id)
@app.task
def send_request_email_change_email_task(
- new_email, old_email, redirect_url, user_id, token
+ new_email, old_email, redirect_url, user_id, token, config
):
+ email_config = EmailConfig(**config)
params = urlencode({"token": token})
redirect_url = prepare_url(params, redirect_url)
send_kwargs, ctx = get_email_context()
ctx["redirect_url"] = redirect_url
- send_templated_mail(
- template_name="account/request_email_change",
+ send_email(
+ config=email_config,
recipient_list=[new_email],
+ template_name="account/request_email_change",
context=ctx,
- **send_kwargs,
)
account_events.customer_email_change_request_event(
user_id=user_id, parameters={"old_email": old_email, "new_email": new_email}
@@ -61,139 +65,155 @@ def send_request_email_change_email_task(
@app.task
-def send_user_change_email_notification_task(recipient_email):
+def send_user_change_email_notification_task(recipient_email, config):
+ email_config = EmailConfig(**config)
send_kwargs, ctx = get_email_context()
- send_templated_mail(
- template_name="account/email_changed_notification",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="account/email_changed_notification",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_account_delete_confirmation_email_task(recipient_email, redirect_url, token):
+def send_account_delete_confirmation_email_task(
+ recipient_email, redirect_url, token, config
+):
+ email_config = EmailConfig(**config)
params = urlencode({"token": token})
delete_url = prepare_url(params, redirect_url)
- _send_delete_confirmation_email(recipient_email, delete_url)
+ _send_delete_confirmation_email(recipient_email, delete_url, email_config)
-def _send_delete_confirmation_email(recipient_email, delete_url):
+def _send_delete_confirmation_email(recipient_email, delete_url, email_config):
send_kwargs, ctx = get_email_context()
ctx["delete_url"] = delete_url
- send_templated_mail(
- template_name="account/account_delete",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="account/account_delete",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_set_user_password_email_task(recipient_email, redirect_url, token):
+def send_set_user_password_email_task(recipient_email, redirect_url, token, config):
+ email_config = EmailConfig(**config)
params = urlencode({"email": recipient_email, "token": token})
password_set_url = prepare_url(params, redirect_url)
- _send_set_password_email(recipient_email, password_set_url)
+ _send_set_password_email(recipient_email, password_set_url, email_config)
-def _send_set_password_email(recipient_email, password_set_url):
+def _send_set_password_email(recipient_email, password_set_url, email_config):
send_kwargs, ctx = get_email_context()
ctx["password_set_url"] = password_set_url
- send_templated_mail(
- template_name="dashboard/customer/set_password",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="dashboard/customer/set_password",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_invoice_email_task(recipient_email, invoice_number, invoice_download_url):
+def send_invoice_email_task(
+ recipient_email, invoice_number, invoice_download_url, config
+):
"""Send an invoice to user of related order with URL to download it."""
+ email_config = EmailConfig(**config)
send_kwargs, ctx = get_email_context()
ctx["number"] = invoice_number
ctx["download_url"] = invoice_download_url
- send_templated_mail(
- template_name="order/send_invoice",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="order/send_invoice",
context=ctx,
- **send_kwargs,
)
@app.task
-def send_order_confirmation_email_task(payload):
+def send_order_confirmation_email_task(payload, config):
"""Send order confirmation email."""
+ email_config = EmailConfig(**config)
recipient_email = payload["recipient_email"]
send_kwargs, ctx = get_email_context()
payload.update(ctx)
- send_templated_mail(
- template_name="order/confirm_order",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="order/confirm_fulfillment",
context=payload,
- **send_kwargs,
)
@app.task
-def send_fulfillment_confirmation_email_task(payload):
+def send_fulfillment_confirmation_email_task(payload, config):
+ email_config = EmailConfig(**config)
recipient_email = payload["recipient_email"]
send_kwargs, ctx = get_email_context()
payload.update(ctx)
- send_templated_mail(
- template_name="order/confirm_fulfillment",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="order/confirm_fulfillment",
context=payload,
- **send_kwargs,
)
@app.task
-def send_fulfillment_update_email_task(payload):
+def send_fulfillment_update_email_task(payload, config):
+ email_config = EmailConfig(**config)
recipient_email = payload["recipient_email"]
send_kwargs, ctx = get_email_context()
payload.update(ctx)
- send_templated_mail(
- template_name="order/update_fulfillment",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="order/update_fulfillment",
context=payload,
- **send_kwargs,
)
@app.task
-def send_payment_confirmation_email_task(payload):
+def send_payment_confirmation_email_task(payload, config):
+ email_config = EmailConfig(**config)
send_kwargs, ctx = get_email_context()
payload.update(ctx)
- send_templated_mail(
+ recipient_email = payload["recipient_email"]
+ send_email(
+ config=email_config,
+ recipient_list=[recipient_email],
template_name="order/payment/confirm_payment",
- recipient_list=[payload["email"]],
context=payload,
- **send_kwargs,
)
@app.task
-def send_order_canceled_email_task(payload):
+def send_order_canceled_email_task(payload, config):
+ email_config = EmailConfig(**config)
recipient_email = payload["recipient_email"]
send_kwargs, ctx = get_email_context()
payload.update(ctx)
- send_templated_mail(
- template_name="order/order_cancel",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="order/order_cancel",
context=payload,
- **send_kwargs,
)
@app.task
-def send_order_refund_email_task(payload):
+def send_order_refund_email_task(payload, config):
+ email_config = EmailConfig(**config)
recipient_email = payload["recipient_email"]
+ # TODO when we replace template define if this context is required
send_kwargs, ctx = get_email_context()
payload.update(ctx)
- send_templated_mail(
- template_name="order/order_refund",
+ send_email(
+ config=email_config,
recipient_list=[recipient_email],
+ template_name="order/order_refund",
context=payload,
- **send_kwargs,
)
diff --git a/saleor/plugins/user_email/tests/conftest.py b/saleor/plugins/user_email/tests/conftest.py
new file mode 100644
index 0000000000..c787c588ba
--- /dev/null
+++ b/saleor/plugins/user_email/tests/conftest.py
@@ -0,0 +1,47 @@
+from unittest.mock import patch
+
+import pytest
+
+from ...manager import get_plugins_manager
+from ..plugin import UserEmailPlugin
+
+
+def user_email_plugin(settings):
+ def fun(
+ host="localhost",
+ port="1025",
+ username=None,
+ password=None,
+ sender_name="Admin Name",
+ sender_address="[email protected]",
+ use_tls=False,
+ use_ssl=False,
+ active=True,
+ ):
+
+ settings.PLUGINS = ["saleor.plugins.user_email.plugin.UserEmailPlugin"]
+ manager = get_plugins_manager()
+ with patch(
+ "saleor.plugins.user_email.plugin.validate_default_email_configuration"
+ ):
+ manager.save_plugin_configuration(
+ UserEmailPlugin.PLUGIN_ID,
+ {
+ "active": active,
+ "configuration": [
+ {"name": "host", "value": host},
+ {"name": "port", "value": port},
+ {"name": "username", "value": username},
+ {"name": "password", "value": password},
+ {"name": "sender_name", "value": sender_name},
+ {"name": "sender_address", "value": sender_address},
+ {"name": "use_tls", "value": use_tls},
+ {"name": "use_ssl", "value": use_ssl},
+ ],
+ },
+ )
+ manager = get_plugins_manager()
+ return manager.plugins[0]
+
+ return fun
diff --git a/saleor/plugins/user_email/tests/conftests.py b/saleor/plugins/user_email/tests/conftests.py
deleted file mode 100644
index 1b45a6644f..0000000000
--- a/saleor/plugins/user_email/tests/conftests.py
+++ /dev/null
@@ -1,18 +0,0 @@
-import pytest
-
-from ...manager import get_plugins_manager
-from ..plugin import UserEmailPlugin
-
-
-def user_email_plugin(settings):
- def fun():
- settings.PLUGINS += ["saleor.plugins.user_email.plugin.UserEmailPlugin"]
- manager = get_plugins_manager()
- manager.save_plugin_configuration(
- UserEmailPlugin.PLUGIN_ID, {"active": True, "configuration": []}
- )
- manager = get_plugins_manager()
- return manager.plugins[0]
-
- return fun
diff --git a/saleor/plugins/user_email/tests/test_plugin.py b/saleor/plugins/user_email/tests/test_plugin.py
new file mode 100644
index 0000000000..aba2a1fbe2
--- /dev/null
+++ b/saleor/plugins/user_email/tests/test_plugin.py
@@ -0,0 +1,174 @@
+from dataclasses import asdict
+from smtplib import SMTPNotSupportedError
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+from django.core.exceptions import ValidationError
+from django.core.mail.backends.smtp import EmailBackend
+
+from ....core.notify_events import NotifyEventType
+from ...models import PluginConfiguration
+from ..notify_events import (
+ send_account_change_email_confirm,
+ send_account_change_email_request,
+ send_account_confirmation,
+ send_account_delete,
+ send_account_password_reset_event,
+ send_account_set_customer_password,
+ send_fulfillment_confirmation,
+ send_fulfillment_update,
+ send_invoice,
+ send_order_canceled,
+ send_order_confirmation,
+ send_order_refund,
+ send_payment_confirmation,
+)
+from ..plugin import get_user_event_map
+
+
+def test_event_map():
+ assert get_user_event_map() == {
+ NotifyEventType.ACCOUNT_CONFIRMATION: send_account_confirmation,
+ NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD: (
+ send_account_set_customer_password
+ ),
+ NotifyEventType.ACCOUNT_DELETE: send_account_delete,
+ NotifyEventType.ACCOUNT_CHANGE_EMAIL_CONFIRM: send_account_change_email_confirm,
+ NotifyEventType.ACCOUNT_CHANGE_EMAIL_REQUEST: send_account_change_email_request,
+ NotifyEventType.ACCOUNT_PASSWORD_RESET: send_account_password_reset_event,
+ NotifyEventType.INVOICE_READY: send_invoice,
+ NotifyEventType.ORDER_CONFIRMATION: send_order_confirmation,
+ NotifyEventType.ORDER_FULFILLMENT_CONFIRMATION: send_fulfillment_confirmation,
+ NotifyEventType.ORDER_FULFILLMENT_UPDATE: send_fulfillment_update,
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION: send_payment_confirmation,
+ NotifyEventType.ORDER_CANCELED: send_order_canceled,
+ NotifyEventType.ORDER_REFUND_CONFIRMATION: send_order_refund,
+ }
+
+
+ "event_type",
+ [
+ NotifyEventType.ACCOUNT_CONFIRMATION,
+ NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD,
+ NotifyEventType.ACCOUNT_DELETE,
+ NotifyEventType.ACCOUNT_CHANGE_EMAIL_CONFIRM,
+ NotifyEventType.ACCOUNT_CHANGE_EMAIL_REQUEST,
+ NotifyEventType.ACCOUNT_PASSWORD_RESET,
+ NotifyEventType.INVOICE_READY,
+ NotifyEventType.ORDER_CONFIRMATION,
+ NotifyEventType.ORDER_FULFILLMENT_CONFIRMATION,
+ NotifyEventType.ORDER_FULFILLMENT_UPDATE,
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
+ NotifyEventType.ORDER_CANCELED,
+ NotifyEventType.ORDER_REFUND_CONFIRMATION,
+ ],
+)
+@patch("saleor.plugins.user_email.plugin.get_user_event_map")
+def test_notify(mocked_get_event_map, event_type, user_email_plugin):
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+ mocked_event = Mock()
+ mocked_get_event_map.return_value = {event_type: mocked_event}
+
+ plugin = user_email_plugin()
+ plugin.notify(event_type, payload, previous_value=None)
+
+ mocked_event.assert_called_with(payload, asdict(plugin.config))
+
+
+@patch("saleor.plugins.user_email.plugin.get_user_event_map")
+def test_notify_event_not_related(mocked_get_event_map, user_email_plugin):
+ event_type = NotifyEventType.STAFF_ORDER_CONFIRMATION
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+ mocked_event = Mock()
+ mocked_get_event_map.return_value = {event_type: mocked_event}
+
+ plugin = user_email_plugin()
+ plugin.notify(event_type, payload, previous_value=None)
+
+ assert not mocked_event.called
+
+
+@patch("saleor.plugins.user_email.plugin.get_user_event_map")
+def test_notify_event_missing_handler(mocked_get_event_map, user_email_plugin):
+ event_type = NotifyEventType.ORDER_PAYMENT_CONFIRMATION
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+ mocked_event_map = MagicMock()
+ mocked_get_event_map.return_value = mocked_event_map
+
+ plugin = user_email_plugin()
+ plugin.notify(event_type, payload, previous_value=None)
+
+ assert not mocked_event_map.__getitem__.called
+
+
+@patch("saleor.plugins.user_email.plugin.get_user_event_map")
+def test_notify_event_plugin_is_not_active(mocked_get_event_map, user_email_plugin):
+ event_type = NotifyEventType.ORDER_PAYMENT_CONFIRMATION
+ payload = {
+ "field1": 1,
+ "field2": 2,
+ }
+
+ plugin = user_email_plugin(active=False)
+ plugin.notify(event_type, payload, previous_value=None)
+
+ assert not mocked_get_event_map.called
+
+
+def test_save_plugin_configuration_tls_and_ssl_are_mutually_exclusive(
+ user_email_plugin,
+):
+ plugin = user_email_plugin()
+ configuration = PluginConfiguration.objects.get()
+ data_to_save = {
+ "configuration": [
+ {"name": "use_tls", "value": True},
+ {"name": "use_ssl", "value": True},
+ ]
+ }
+ with pytest.raises(ValidationError):
+ plugin.save_plugin_configuration(configuration, data_to_save)
+
+
[email protected](EmailBackend, "open")
+def test_save_plugin_configuration(mocked_open, user_email_plugin):
+ plugin = user_email_plugin()
+ configuration = PluginConfiguration.objects.get()
+ data_to_save = {
+ "configuration": [
+ {"name": "use_tls", "value": False},
+ {"name": "use_ssl", "value": True},
+ ]
+ }
+
+ plugin.save_plugin_configuration(configuration, data_to_save)
+
+ mocked_open.assert_called_with()
+
+
[email protected](EmailBackend, "open")
+def test_save_plugin_configuration_incorrect_email_backend_configuration(
+ mocked_open, user_email_plugin
+):
+ plugin = user_email_plugin()
+ mocked_open.side_effect = SMTPNotSupportedError()
+ configuration = PluginConfiguration.objects.get()
+ data_to_save = {
+ "configuration": [
+ {"name": "use_tls", "value": False},
+ {"name": "use_ssl", "value": True},
+ ]
+ }
+
+ with pytest.raises(ValidationError):
+ plugin.save_plugin_configuration(configuration, data_to_save)
diff --git a/saleor/site/models.py b/saleor/site/models.py
index 0dd9a7d720..2a984c355e 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -60,6 +60,8 @@ class SiteSettings(models.Model):
company_address = models.ForeignKey(
"account.Address", blank=True, null=True, on_delete=models.SET_NULL
)
+ # FIXME these values are configurable from email plugin. Not needed to be placed
+ # here
default_mail_sender_name = models.CharField(
max_length=settings.DEFAULT_MAX_EMAIL_DISPLAY_NAME_LENGTH,
blank=True,