import logging import aiosmtplib from asgiref.sync import sync_to_async from channels.layers import get_channel_layer from mail.models import Email, EventAddress from notify_sessions.models import SystemEvent from tickets.models import IssueThread def collect_references(issue_thread): mails = issue_thread.emails.order_by('timestamp') references = [] for mail in mails: if mail.reference: references.append(mail.reference) return references def make_reply(reply_email, references=None): from email.message import EmailMessage from core.settings import MAIL_DOMAIN reply = EmailMessage() reply["From"] = reply_email.sender reply["To"] = reply_email.recipient reply["Subject"] = reply_email.subject if reply_email.in_reply_to: reply["In-Reply-To"] = reply_email.in_reply_to if reply_email.reference: reply["Message-ID"] = reply_email.reference else: reply["Message-ID"] = reply_email.id + "@" + MAIL_DOMAIN reply_email.reference = reply["Message-ID"] reply_email.save() if references: reply["References"] = " ".join(references) reply.set_content(reply_email.body) return reply async def send_smtp(message, log): log.info('Sending message to %s' % message['To']) await aiosmtplib.send(message, hostname="127.0.0.1", port=25, use_tls=False, start_tls=False) def find_active_issue_thread(in_reply_to): reply_to = Email.objects.filter(reference=in_reply_to) if reply_to.exists(): return reply_to.first().issue_thread else: return IssueThread.objects.create() class LMTPHandler: async def handle_RCPT(self, server, session, envelope, address, rcpt_options): from core.settings import MAIL_DOMAIN if not address.endswith('@' + MAIL_DOMAIN): return '550 not relaying to that domain' envelope.rcpt_tos.append(address) return '250 OK' async def handle_DATA(self, server, session, envelope): import email log = logging.getLogger('mail.log') log.setLevel(logging.DEBUG) log.info('Message from %s' % envelope.mail_from) log.info('Message for %s' % envelope.rcpt_tos) log.info('Message data:\n') try: parsed = email.message_from_bytes(envelope.content) body = "" if parsed.is_multipart(): for part in parsed.walk(): ctype = part.get_content_type() cdispo = str(part.get('Content-Disposition')) # skip any text/plain (txt) attachments if ctype == 'text/plain' and 'attachment' not in cdispo: body = part.get_payload(decode=True) else: log.info("Attachment", ctype, cdispo) else: body = parsed.get_payload(decode=True) log.info(body) header_from = parsed.get('From') header_to = parsed.get('To') header_in_reply_to = parsed.get('In-Reply-To') header_message_id = parsed.get('Message-ID') if header_from != envelope.mail_from: log.warning("Header from does not match envelope from") log.info(f"Header from: {header_from}, envelope from: {envelope.mail_from}") if header_to != envelope.rcpt_tos[0]: log.warning("Header to does not match envelope to") log.info(f"Header to: {header_to}, envelope to: {envelope.rcpt_tos[0]}") recipient = envelope.rcpt_tos[0] sender = envelope.mail_from target_event = None try: address_map = await sync_to_async(EventAddress.objects.get)(address=recipient) if address_map.event: target_event = address_map.event except EventAddress.DoesNotExist: pass active_issue_thread = await sync_to_async(find_active_issue_thread)(header_in_reply_to) email = await sync_to_async(Email.objects.create)(sender=sender, recipient=recipient, body=body.decode('utf-8'), subject=parsed.get('Subject'), reference=header_message_id, in_reply_to=header_in_reply_to, raw=envelope.content.decode('utf-8'), event=target_event, issue_thread=active_issue_thread) log.info(f"Created email {email.id}") systemevent = await sync_to_async(SystemEvent.objects.create)(type='email received', reference=email.id) log.info(f"Created system event {systemevent.id}") channel_layer = get_channel_layer() await channel_layer.group_send( 'general', {"type": "generic.event", "name": "send_message_to_frontend", "event_id": systemevent.id, "message": "email received"} ) log.info(f"Sent message to frontend") references = await sync_to_async(collect_references)(active_issue_thread) reply_email = await sync_to_async(Email.objects.create)(sender=recipient, # "noreply@" + MAIL_DOMAIN, recipient=sender, body="Thank you for your message.", subject="Message received", in_reply_to=header_message_id, event=target_event, issue_thread=active_issue_thread) await send_smtp(make_reply(reply_email, references), log) log.info("Sent reply") return '250 Message accepted for delivery' except Exception as e: log.error(e) return '550 Message rejected'