| 7 | |
| 8 | |
| 9 | class SendEmailHandler(MessageHandler): |
| 10 | def can_handle(self, action: str) -> bool: |
| 11 | return action in [EmailAction.send_email.value] |
| 12 | |
| 13 | async def handle(self, context: MessageContext) -> ProcessingResult: |
| 14 | try: |
| 15 | to = context.payload.get("to") |
| 16 | subject = context.payload.get("subject") |
| 17 | body = context.payload.get("body") |
| 18 | cc = context.payload.get("cc") |
| 19 | bcc = context.payload.get("bcc") |
| 20 | body_type = context.payload.get("body_type") |
| 21 | attachments = context.payload.get("attachments") |
| 22 | if to is None or subject is None or body is None: |
| 23 | raise ValueError("🛑 Missing required fields in message") |
| 24 | self.container.email_service().send_email( |
| 25 | message=EMessage( |
| 26 | to=[str(email) for email in to] if isinstance(to, list) else str(to), |
| 27 | cc=[str(email) for email in cc] if isinstance(cc, list) else ([str(cc)] if cc else []), |
| 28 | bcc=[str(email) for email in bcc] if isinstance(bcc, list) else ([str(bcc)] if bcc else []), |
| 29 | subject=str(subject), |
| 30 | body=str(body), |
| 31 | body_type=body_type or "html", |
| 32 | attachments=[str(attachment) for attachment in attachments] |
| 33 | if isinstance(attachments, list) |
| 34 | else ([str(attachments)] if attachments else []), |
| 35 | ) |
| 36 | ) |
| 37 | return ProcessingResult.SUCCESS |
| 38 | except Exception as e: |
| 39 | self.logger.error(f"🛑 Failed to send email: {e}", error=traceback.extract_tb(e.__traceback__)[-1]) |
| 40 | return ProcessingResult.REJECT |