Dorian Turba
Dorian Turba

Reputation: 3755

Fake SMTP server not supporting auth

Fake SMTP server not supporting auth

I have a function that create a SMTP client, login onto a server, and send mails. I want to create a unit-test with a fake SMTP server that will write the email content into a io stream instead of sending the email.

Everything works great except the login part that raise this error:

smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.

MRE

import email.message
import io
import smtplib

import aiosmtpd.controller
import aiosmtpd.handlers
import aiosmtpd.smtp


def foobar(host, port):
    client = smtplib.SMTP(host=host, port=port)
    message = email.message.EmailMessage()
    message["From"] = "[email protected]"
    message["To"] = "[email protected]"
    message["Subject"] = "subject"
    message.set_content("Hello World")
    with client as session:
        session.login("foo", "bar")
        session.send_message(message)


def test_foobar():
    io_stream = io.StringIO()
    handler = aiosmtpd.handlers.Debugging(io_stream)
    controller = aiosmtpd.controller.Controller(handler)
    controller.start()
    foobar(controller.hostname, controller.port)
    controller.stop()

    assert "Hello World" in io_stream.getvalue()

Requirements

pip install aiosmtpd

Tentatives to fix:

Add an Authenticator

From documentation:

aiosmtpd authentication is always activated, but attempts to authenticate will always be rejected unless the authenticator parameter of SMTP is set to a valid & working Authenticator Callback.

[...]

def test_foobar():
    
    def authenticator(*args, **kwargs):
        return aiosmtpd.smtp.AuthResult(success=True)
    
    [...]
    controller = aiosmtpd.controller.Controller(handler, authenticator=authenticator)
    [...]

Result: Same error

Add handle_AUTH and auth_MECHANISM always returning AuthResult(success=True)

Documentation

[...]

class CustomDebugging(aiosmtpd.handlers.Debugging):

    async def handle_AUTH(self, *arg, **kwargs):
        return aiosmtpd.smtp.AuthResult(success=True)

    async def auth_PLAIN(self, *arg, **kwargs):
        return aiosmtpd.smtp.AuthResult(success=True)

    async def auth_LOGIN(self, *arg, **kwargs):
        return aiosmtpd.smtp.AuthResult(success=True)

def test_foobar():

    def authenticator(*args, **kwargs):
        return aiosmtpd.smtp.AuthResult(success=True)

    handler = CustomDebugging(io_stream)
    controller = aiosmtpd.controller.Controller(
        handler, authenticator=authenticator
    )
    [...]

Result: Same error

What should I do to fix this issue?

Upvotes: 2

Views: 241

Answers (0)

Related Questions