Implement an SMTP server using aiosmtpd and a mail sender script. The server handles incoming messages and prints their content, while the mail sender constructs and sends an email message. These changes enable local email testing for the CNP assignment, improving development efficiency.
33 lines
1 KiB
Python
33 lines
1 KiB
Python
import asyncio
|
|
import uvloop
|
|
from aiosmtpd.controller import Controller
|
|
|
|
# handler that just prints the message content
|
|
class PrintHandler:
|
|
async def handle_DATA(self, server, session, envelope):
|
|
print("Message from:", envelope.mail_from)
|
|
print("Recipients:", envelope.rcpt_tos)
|
|
print("Message data:")
|
|
print(envelope.content.decode('utf8', errors='replace'))
|
|
print("End of message")
|
|
# Respond with a success code
|
|
return '250 Message accepted for delivery'
|
|
|
|
# uvloop for better performance
|
|
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
|
|
|
|
def run_server():
|
|
# SMTP server controller, binding to localhost on port 25
|
|
controller = Controller(PrintHandler(), hostname='127.0.0.1', port=25)
|
|
controller.start()
|
|
print("SMTP server running on port 25. Press Ctrl+C to stop.")
|
|
try:
|
|
# Run forever
|
|
asyncio.get_event_loop().run_forever()
|
|
except KeyboardInterrupt:
|
|
pass
|
|
finally:
|
|
controller.stop()
|
|
|
|
if __name__ == '__main__':
|
|
run_server()
|