import ssl
import smtplib


def configure_smtp(settings_dict):
    """
    Configures the SMTP gateway.

    Args:
        settings_dict (dict)

    Returns:
        smtplib.SMTP:
            The SMTP connection.

    Raises:
        Exception:
            If anything goes wrong.
    """

    # Create a SSL context
    context = ssl.create_default_context()

    # Try to connect to the server
    try:
        server = smtplib.SMTP(settings_dict["send_email"]["email_host"], settings_dict["send_email"]["email_port"])
        server.ehlo()
        server.starttls(context=context)
        server.ehlo()
        server.login(settings_dict["send_email"]["email_user"], settings_dict["send_email"]["email_password"])

        return server

    except Exception as e:
        raise Exception(f"An exception occurred when logging onto the email server:\n{e}")