Skip to content

Commit

Permalink
update email_service to use my own wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
yingshaoxo committed Mar 20, 2023
1 parent 329b05e commit ec5c887
Showing 1 changed file with 47 additions and 23 deletions.
70 changes: 47 additions & 23 deletions email_platform/email_service.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,59 @@
from typing import Any
from aiosmtpd.controller import Controller
from typing import Any, Callable

from email.parser import Parser
from email.policy import default
class SMTP_Service():
def __init__(self, host: str, port: int, handler: Callable[[str, str, str], None]):
"""
host: 0.0.0.0
port: 25
handler: (from: str, to: str, content: str) => None
"""
from aiosmtpd.controller import Controller

class CustomHandler:
async def handle_DATA(self, server: Any, session: Any, envelope: Any):
mail_from = envelope.mail_from
data = envelope.content
class CustomHandler:
async def handle_DATA(self, server: Any, session: Any, envelope: Any):
mail_from = envelope.mail_from
mail_to = envelope.rcpt_tos
data = envelope.content

try:
headers = Parser(policy=default).parsestr(data.decode(encoding="utf-8"))
content = headers['subject']
print(f"mail_from: {mail_from}")
print(content)
except Exception as e:
print(e)
return '500 Could not process your message'
try:
print(f"mail_from: {mail_from}")
print("\n\n---\n\n")
handler(mail_from, mail_to, data.decode(encoding="utf-8"))
except Exception as e:
print(e)
return '500 Could not process your message'

return '250 OK'
return '250 OK'

self.host = host
self.port = port
self.custom_handler = CustomHandler()
self.controller = Controller(self.custom_handler, hostname=host, port=port)

if __name__ == '__main__':
handler = CustomHandler()
controller = Controller(handler, hostname='0.0.0.0', port=25)
controller.start()
input('SMTP server running. (Press Return to stop server and exit.\n\n')
controller.stop()
def start(self):
from time import sleep
self.controller.start()
print(f'SMTP server is running on {self.host}:{self.port}.\n\n')
while True:
sleep(5)

def stop(self):
self.controller.stop()


if __name__ == '__main__':
def handle_email(from_: str, to: str, message: str):
print(from_)
print(to)
print(message)

smtp_service = SMTP_Service(
host="0.0.0.0",
port=25,
handler=handle_email
)

smtp_service.start()

# import smtpd
# import asyncore
Expand Down

0 comments on commit ec5c887

Please sign in to comment.