74 lines
2.5 KiB
Python
74 lines
2.5 KiB
Python
from typing import Optional
|
|
|
|
from django.core.mail import EmailMessage, get_connection
|
|
from pydantic import BaseModel, EmailStr
|
|
|
|
from notify.delivery.base import DeliveryProvider, render_notification_template
|
|
from notify.delivery.exceptions import DeliveryError, PermanentDeliveryError
|
|
from notify.models import DeliveryChannel, DeliveryEmailConfig, NotificationRecipient
|
|
|
|
__all__ = [
|
|
'EmailTargetSchema',
|
|
'EmailDeliveryProvider',
|
|
]
|
|
|
|
|
|
class EmailTargetSchema(BaseModel):
|
|
email: EmailStr
|
|
|
|
|
|
class EmailDeliveryProvider(DeliveryProvider):
|
|
channel = DeliveryChannel.EMAIL
|
|
target_schema = EmailTargetSchema
|
|
supports_codes = True
|
|
|
|
def target_key(self, target: EmailTargetSchema) -> str:
|
|
return target.email.lower()
|
|
|
|
def send(self, recipient: NotificationRecipient) -> None:
|
|
subject, body = render_notification_template(DeliveryChannel.EMAIL, recipient)
|
|
self.send_message(
|
|
self.parse_target(recipient.target),
|
|
subject,
|
|
body,
|
|
attachments=recipient.notification.attachments.all(),
|
|
)
|
|
self.mark_sent(recipient)
|
|
|
|
def send_message(
|
|
self,
|
|
target: Optional[EmailTargetSchema],
|
|
subject: str,
|
|
body: str,
|
|
attachments=(),
|
|
) -> None:
|
|
delivery_config = DeliveryEmailConfig.get_default()
|
|
if delivery_config is None:
|
|
raise DeliveryError("No default email delivery config")
|
|
if target is None:
|
|
raise PermanentDeliveryError("Email recipient has no email")
|
|
|
|
try:
|
|
email_connection = get_connection(**delivery_config.get_connection_config())
|
|
msg = EmailMessage(
|
|
subject,
|
|
body=body,
|
|
from_email=delivery_config.from_email,
|
|
to=[target.email],
|
|
connection=email_connection,
|
|
)
|
|
msg.content_subtype = "html"
|
|
for attachment in attachments:
|
|
with attachment.file.open("rb") as uploaded:
|
|
payload = uploaded.read()
|
|
msg.attach(attachment.name, payload, attachment.content_type)
|
|
sent = msg.send(fail_silently=False)
|
|
except ValueError as exc:
|
|
raise PermanentDeliveryError(str(exc)) from exc
|
|
except DeliveryError:
|
|
raise
|
|
except Exception as exc:
|
|
raise DeliveryError("Email delivery failed") from exc
|
|
if not sent:
|
|
raise DeliveryError("Email was not accepted for delivery")
|