askrobots / dbbasic-email
Public
Email for dbbasic apps: Unix-style local mailboxes, and SMTP delivery through dbbasic-queue.
__init__.py · 4.8 KB · 190 lines
| 1 | """ |
| 2 | dbbasic-email: Simple email queue with Unix mail support |
| 3 | |
| 4 | Local mail (Unix-style) + External email (SMTP) via dbbasic-queue |
| 5 | """ |
| 6 | |
| 7 | import os |
| 8 | import time |
| 9 | import smtplib |
| 10 | import secrets |
| 11 | from email.message import EmailMessage |
| 12 | from pathlib import Path |
| 13 | |
| 14 | __version__ = "1.0.0" |
| 15 | |
| 16 | MAIL_DIR = os.getenv('MAIL_DIR', 'var/mail') |
| 17 | SMTP_HOST = os.getenv('SMTP_HOST', 'localhost') |
| 18 | SMTP_PORT = int(os.getenv('SMTP_PORT', '25')) |
| 19 | SMTP_USER = os.getenv('SMTP_USER', '') |
| 20 | SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '') |
| 21 | FROM_ADDR = os.getenv('FROM_ADDR', 'noreply@example.com') |
| 22 | |
| 23 | |
| 24 | def mail(username, subject, body): |
| 25 | """ |
| 26 | Send local mail to user (Unix mail) |
| 27 | |
| 28 | Args: |
| 29 | username (str): Local username |
| 30 | subject (str): Email subject |
| 31 | body (str): Email body (plain text) |
| 32 | |
| 33 | Returns: |
| 34 | str: Message ID |
| 35 | """ |
| 36 | mailbox = Path(MAIL_DIR) / username |
| 37 | mailbox.parent.mkdir(parents=True, exist_ok=True) |
| 38 | |
| 39 | message_id = f"<{secrets.token_hex(8)}@localhost>" |
| 40 | |
| 41 | with mailbox.open('a') as f: |
| 42 | f.write(f"From system {time.ctime()}\n") |
| 43 | f.write(f"Subject: {subject}\n") |
| 44 | f.write(f"Message-ID: {message_id}\n") |
| 45 | f.write(f"\n{body}\n\n") |
| 46 | |
| 47 | return message_id |
| 48 | |
| 49 | |
| 50 | def send_email(to, subject, body, from_addr=None): |
| 51 | """ |
| 52 | Queue external email for SMTP delivery |
| 53 | |
| 54 | Args: |
| 55 | to (str): Email address |
| 56 | subject (str): Email subject |
| 57 | body (str): Email body (plain text) |
| 58 | from_addr (str, optional): From address |
| 59 | |
| 60 | Returns: |
| 61 | str: Job ID |
| 62 | """ |
| 63 | try: |
| 64 | from dbbasic_queue import enqueue |
| 65 | |
| 66 | from_addr = from_addr or FROM_ADDR |
| 67 | |
| 68 | job_id = enqueue('send_email', { |
| 69 | 'to': to, |
| 70 | 'from': from_addr, |
| 71 | 'subject': subject, |
| 72 | 'body': body |
| 73 | }) |
| 74 | |
| 75 | return job_id |
| 76 | except ImportError: |
| 77 | raise ImportError("dbbasic-queue required for send_email(). Install with: pip install dbbasic-queue") |
| 78 | |
| 79 | |
| 80 | def send_template(to, template, context): |
| 81 | """ |
| 82 | Send email using template |
| 83 | |
| 84 | Args: |
| 85 | to (str): Email address |
| 86 | template (str): Template name |
| 87 | context (dict): Template variables |
| 88 | |
| 89 | Returns: |
| 90 | str: Job ID |
| 91 | """ |
| 92 | template_path = Path(f'templates/email/{template}.txt') |
| 93 | if not template_path.exists(): |
| 94 | raise FileNotFoundError(f"Template not found: {template}") |
| 95 | |
| 96 | template_text = template_path.read_text() |
| 97 | |
| 98 | lines = template_text.split('\n') |
| 99 | subject = '' |
| 100 | body_lines = [] |
| 101 | in_body = False |
| 102 | |
| 103 | for line in lines: |
| 104 | if line.startswith('Subject:'): |
| 105 | subject = line.replace('Subject:', '').strip() |
| 106 | elif line == '': |
| 107 | in_body = True |
| 108 | elif in_body: |
| 109 | body_lines.append(line) |
| 110 | |
| 111 | body = '\n'.join(body_lines) |
| 112 | |
| 113 | subject = subject.format(**context) |
| 114 | body = body.format(**context) |
| 115 | |
| 116 | return send_email(to, subject, body) |
| 117 | |
| 118 | |
| 119 | def read_mail(username, limit=50): |
| 120 | """ |
| 121 | Read user's mailbox (local mail) |
| 122 | |
| 123 | Args: |
| 124 | username (str): Username |
| 125 | limit (int): Max messages to return |
| 126 | |
| 127 | Returns: |
| 128 | list: List of message dicts |
| 129 | """ |
| 130 | mailbox = Path(MAIL_DIR) / username |
| 131 | if not mailbox.exists(): |
| 132 | return [] |
| 133 | |
| 134 | messages = [] |
| 135 | current_msg = None |
| 136 | |
| 137 | with mailbox.open('r') as f: |
| 138 | for line in f: |
| 139 | if line.startswith('From '): |
| 140 | if current_msg: |
| 141 | messages.append(current_msg) |
| 142 | current_msg = { |
| 143 | 'date': line.replace('From system ', '').strip(), |
| 144 | 'subject': '', |
| 145 | 'message_id': '', |
| 146 | 'body': '' |
| 147 | } |
| 148 | elif current_msg: |
| 149 | if line.startswith('Subject:'): |
| 150 | current_msg['subject'] = line.replace('Subject:', '').strip() |
| 151 | elif line.startswith('Message-ID:'): |
| 152 | current_msg['message_id'] = line.replace('Message-ID:', '').strip() |
| 153 | elif line.strip(): |
| 154 | current_msg['body'] += line |
| 155 | |
| 156 | if current_msg: |
| 157 | messages.append(current_msg) |
| 158 | |
| 159 | return list(reversed(messages))[:limit] |
| 160 | |
| 161 | |
| 162 | def _smtp_send_handler(payload): |
| 163 | """ |
| 164 | Queue worker handler for sending SMTP email |
| 165 | |
| 166 | Called by dbbasic-queue worker |
| 167 | """ |
| 168 | msg = EmailMessage() |
| 169 | msg['From'] = payload['from'] |
| 170 | msg['To'] = payload['to'] |
| 171 | msg['Subject'] = payload['subject'] |
| 172 | msg.set_content(payload['body']) |
| 173 | |
| 174 | if SMTP_USER: |
| 175 | with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp: |
| 176 | smtp.starttls() |
| 177 | smtp.login(SMTP_USER, SMTP_PASSWORD) |
| 178 | smtp.send_message(msg) |
| 179 | else: |
| 180 | with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as smtp: |
| 181 | smtp.send_message(msg) |
| 182 | |
| 183 | return {'sent_at': time.time(), 'to': payload['to']} |
| 184 | |
| 185 | |
| 186 | QUEUE_HANDLERS = { |
| 187 | 'send_email': _smtp_send_handler |
| 188 | } |
| 189 | |
| 190 | __all__ = ['mail', 'send_email', 'send_template', 'read_mail', 'QUEUE_HANDLERS'] |