Server SMTP con Autentificazione, in Python
Attenzione! Questo è un esempio molto semplice e non sicuro di un Server SMTP con sistema di autenticazione. In un vero server SMTP, dovresti utilizzare un meccanismo di autenticazione altamente professionale come SCRAM o Kerberos e memorizzare le password in modo sicuro (non in chiaro come in questo esempio), utilizzando anche la crittografia per proteggere le informazioni di autenticazione durante la trasmissione.
import asyncio
import base64
from aiosmtpd.controller import Controller
from aiosmtpd.handlers import Message
from aiosmtpd.smtp import Envelope, Session, SMTP
class AuthMessageHandler(Message):
async def handle_AUTH(self, server: SMTP, session: Session, envelope: Envelope, mechanism: str, auth_data: str):
if mechanism != 'PLAIN':
return '504 Unrecognized authentication type.'
username, password = self.decode_auth_data(auth_data)
if username == 'testuser' and password == 'testpass':
return '235 Authentication successful.'
else:
return '535 Authentication credentials invalid'
def decode_auth_data(self, auth_data):
auth_data = base64.b64decode(auth_data).decode()
null, username, password = auth_data.split('\0')
return username, password
async def handle_DATA(self, server, session, envelope):
print('Messaggio ricevuto da:', session.peer)
print('Da:', envelope.mail_from)
print('A:', envelope.rcpt_tos)
print('Messaggio:')
print(envelope.content)
return '250 Message accepted for delivery'
handler = AuthMessageHandler()
controller = Controller(handler, hostname='localhost', port=1025)
controller.start()
try:
asyncio.get_event_loop().run_forever()
except KeyboardInterrupt:
pass
finally:
controller.stop()