diff --git a/pyas2/models.py b/pyas2/models.py index a323551..af0b20a 100644 --- a/pyas2/models.py +++ b/pyas2/models.py @@ -23,6 +23,7 @@ from pyas2 import settings from pyas2.utils import run_post_send +from pyas2.utils import notify_error logger = logging.getLogger("pyas2") @@ -511,6 +512,7 @@ def send_message(self, header, payload): self.detailed_status = ( f"Partner failed to process message: {mdn_detailed_status}" ) + notify_error(self) if mdn_detailed_status != "mdn-not-found": Mdn.objects.create_from_as2mdn( as2mdn=as2mdn, message=self, status="R" diff --git a/pyas2/utils.py b/pyas2/utils.py index f749966..2b67006 100644 --- a/pyas2/utils.py +++ b/pyas2/utils.py @@ -2,6 +2,8 @@ import logging import os from string import Template +from django.core.mail import mail_managers +from django.utils.timezone import localtime logger = logging.getLogger("pyas2") @@ -48,3 +50,32 @@ def run_post_receive(message, full_filename): # Execute the command os.system(command.safe_substitute(variables)) + + +def notify_error(message): + """ Notify via email about errors with transmission of messages """ + + try: + email_subject = "pyAS2 Error" + email_body = ( + "Error: Message transmission failed!" + "\n\nMessage ID: %(id)s" + "\nDate/Time: %(time)s" + "\nOrganization: %(org)s" + "\nPartner: %(prt)s" + "\nDirection: %(dir)s" + "\nDetailed Status: %(stat)s" + % { + "id": message.message_id, + "time": localtime(message.timestamp).strftime("%Y-%m-%d %H:%M:%S"), + "org": message.organization, + "prt": message.partner, + "dir": message.get_direction_display(), + "stat": message.detailed_status, + } + ) + mail_managers( + email_subject, email_body, fail_silently=False, + ) + except Exception as msg: + logger.warning("Error sending email notification: %(msg)s", {"msg": msg}) diff --git a/pyas2/views.py b/pyas2/views.py index 499f0e1..8881baf 100644 --- a/pyas2/views.py +++ b/pyas2/views.py @@ -24,6 +24,7 @@ from pyas2.models import PublicCertificate from pyas2.utils import run_post_receive from pyas2.utils import run_post_send +from pyas2.utils import notify_error from pyas2.forms import SendAs2MessageForm logger = logging.getLogger("pyas2") @@ -112,6 +113,7 @@ def post(self, request, *args, **kwargs): message.detailed_status = ( f"Partner failed to process message: {detailed_status}" ) + notify_error(message) # Save the message and create the mdn message.save() Mdn.objects.create_from_as2mdn(as2mdn=as2mdn, message=message, status="R") @@ -152,6 +154,10 @@ def post(self, request, *args, **kwargs): if status == "processed": run_post_receive(message, full_fn) + # notify of error + if message.status == "E": + notify_error(message) + # Return the mdn in case of sync else return text message if as2mdn and as2mdn.mdn_mode == "SYNC": message.mdn = Mdn.objects.create_from_as2mdn(